-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReentrantLockOrder.java
More file actions
41 lines (39 loc) · 1.02 KB
/
ReentrantLockOrder.java
File metadata and controls
41 lines (39 loc) · 1.02 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
import java.util.concurrent.locks.ReentrantLock;
class ReentrantLockOrder {
private int primaryAccountBalance;
private final ReentrantLock primaryLock = new ReentrantLock();
private int savingsAccountBalance;
private final ReentrantLock savingsLock = new ReentrantLock();
public boolean transferToSavings(int amount) {
try {
primaryLock.lock();
savingsLock.lock();
if (amount>0 && primaryAccountBalance>=amount) {
primaryAccountBalance -= amount;
savingsAccountBalance += amount;
return true;
}
} finally {
savingsLock.unlock();
primaryLock.unlock();
}
return false;
}
public boolean transferToPrimary(int amount) {
// AVOID: lock order is different from "transferToSavings"
// and may result in deadlock
try {
savingsLock.lock();
primaryLock.lock();
if (amount>0 && primaryAccountBalance>=amount) {
primaryAccountBalance -= amount;
savingsAccountBalance += amount;
return true;
}
} finally {
primaryLock.unlock();
savingsLock.unlock();
}
return false;
}
}