-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBank.java
More file actions
45 lines (36 loc) · 1.2 KB
/
Bank.java
File metadata and controls
45 lines (36 loc) · 1.2 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
package com.javaMultithreading;
import java.util.concurrent.ConcurrentHashMap;
public class Bank {
private ConcurrentHashMap<Integer, BankAccount> accounts = new ConcurrentHashMap<>();
public void AddAccount(BankAccount account) {
accounts.put(account.getAccountNumber(), account);
}
public BankAccount getAccount(int accNo) {
return accounts.get(accNo);
}
public boolean transfer(int fromAcc, int toAcc, double amount) {
BankAccount from = accounts.get(fromAcc);
BankAccount to = accounts.get(toAcc);
if(from == null || to == null)
return false;
BankAccount firstLock = fromAcc < toAcc ? from: to;
BankAccount secondLock = fromAcc < toAcc ? to: from;
firstLock.getLock().lock();
secondLock.getLock().lock();
try {
if(!from.withdraw(amount)) return false;
to.deposit(amount);
System.out.println("Transferred"+amount+"from A/C"+fromAcc+"to A/C"+toAcc);
return true;
}
finally {
secondLock.getLock().unlock();
firstLock.getLock().unlock();
}
}
public void printAllBalances() {
for(BankAccount acc: accounts.values()) {
System.out.println("A/C"+acc.getAccountNumber()+"Balance: "+acc.getBalance());
}
}
}