-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathBankAccount.java
More file actions
69 lines (59 loc) · 1.5 KB
/
BankAccount.java
File metadata and controls
69 lines (59 loc) · 1.5 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
package Banking;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private final int id;
private int balance;
private final Lock lock = new ReentrantLock();
public BankAccount(int id, int initialBalance) {
this.id = id;
this.balance = initialBalance;
}
public int getId() {
return id;
}
public int getBalance() {
lock.lock();
try {
return balance;
} finally {
lock.unlock();
}
}
public Lock getLock() {
return lock;
}
public void deposit(int amount) {
lock.lock();
try {
balance += amount;
} finally {
lock.unlock();
}
}
public void withdraw(int amount) {
lock.lock();
try {
balance -= amount;
} finally {
lock.unlock();
}
}
public void transfer(BankAccount target, int amount) {
// Acquire locks in consistent order to prevent deadlock
BankAccount first = this.id < target.id ? this : target;
BankAccount second = this.id < target.id ? target : this;
first.lock.lock();
try {
second.lock.lock();
try {
this.balance -= amount;
target.balance += amount;
} finally {
second.lock.unlock();
}
} finally {
first.lock.unlock();
}
}
}