-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
82 lines (64 loc) · 3.25 KB
/
Copy pathMain.java
File metadata and controls
82 lines (64 loc) · 3.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import DuplicatePurchaseException;
import FlashSaleService;
public class Main {
public static void main(String[] args) throws InterruptedException {
int totalItems = 10;
int totalConcurrentUsers = 100;
double itemPrice = 499.99;
Product phone = new Product("P100", "Flagship Smartphone");
FlashSaleService saleService = new FlashSaleService(phone, totalItems);
// Thread pool with 20 worker threads
ExecutorService executor = Executors.newFixedThreadPool(totalConcurrentUsers);
CountDownLatch readyLatch = new CountDownLatch(totalConcurrentUsers);
CountDownLatch startLatch = new CountDownLatch(1);
// Thread-safe list to store successful purchase records for analytics
List<PurchaseRecord> purchaseRecords = new CopyOnWriteArrayList<>();
AtomicInteger successCount = new AtomicInteger(0);
AtomicInteger outOfStockCount = new AtomicInteger(0);
System.out.println("=== FLASH SALE STARTED ===");
System.out.println("Initial Stock: " + totalItems);
System.out.println("Simulating " + totalConcurrentUsers + " buyers...\n");
for (int i = 1; i <= totalConcurrentUsers; i++) {
final String userId = "User_" + i;
executor.submit(new Runnable() {
@Override
public void run() {
try {
// Signal that this thread is ready
readyLatch.countDown();
// Wait until ALL 100 threads are ready at the starting line
startLatch.await();
// Attempt the purchase
saleService.purchase(userId);
// If successful, log the purchase
successCount.incrementAndGet();
purchaseRecords.add(new PurchaseRecord(userId, phone.getProductId(), itemPrice));
System.out.println(" SUCCESS: " + userId + " secured an item!");
} catch (OutOfStockException e) {
outOfStockCount.incrementAndGet();
} catch (DuplicatePurchaseException e) {
System.out.println(" REJECTED: " + e.getMessage());
} catch (InterruptedException e) {
}
}
});
}
// Wait for all 100 threads to reach the starting line
readyLatch.await();
// BANG! Release all threads simultaneously
startLatch.countDown();
// Gracefully shutdown the executor and wait for execution to complete
executor.shutdown();
boolean finished = executor.awaitTermination(10, TimeUnit.SECONDS);
if (finished) {
System.out.println("\n=== SALE COMPLETED ===");
// Run Stream API Analytics Report
SaleAnalytics.generateReport(purchaseRecords, totalConcurrentUsers);
} else {
System.out.println("\n Error: Simulation timed out.");
}
}
}