forked from ashishps1/awesome-low-level-design
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStockBroker.java
69 lines (58 loc) · 2.03 KB
/
StockBroker.java
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
package onlinestockbrokeragesystem;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class StockBroker {
private static StockBroker instance;
private final Map<String, Account> accounts;
private final Map<String, Stock> stocks;
private final Queue<Order> orderQueue;
private final AtomicInteger accountIdCounter;
private StockBroker() {
accounts = new ConcurrentHashMap<>();
stocks = new ConcurrentHashMap<>();
orderQueue = new ConcurrentLinkedQueue<>();
accountIdCounter = new AtomicInteger(1);
}
public static synchronized StockBroker getInstance() {
if (instance == null) {
instance = new StockBroker();
}
return instance;
}
public void createAccount(User user, double initialBalance) {
String accountId = generateAccountId();
Account account = new Account(accountId, user, initialBalance);
accounts.put(accountId, account);
}
public Account getAccount(String accountId) {
return accounts.get(accountId);
}
public void addStock(Stock stock) {
stocks.put(stock.getSymbol(), stock);
}
public Stock getStock(String symbol) {
return stocks.get(symbol);
}
public void placeOrder(Order order) {
orderQueue.offer(order);
processOrders();
}
private void processOrders() {
while (!orderQueue.isEmpty()) {
Order order = orderQueue.poll();
try {
order.execute();
} catch (InsufficientFundsException | InsufficientStockException e) {
// Handle exception and notify user
System.out.println("Order failed: " + e.getMessage());
}
}
}
private String generateAccountId() {
int accountId = accountIdCounter.getAndIncrement();
return "A" + String.format("%03d", accountId);
}
}