forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertToWriteLock.java
More file actions
35 lines (26 loc) · 944 Bytes
/
Copy pathConvertToWriteLock.java
File metadata and controls
35 lines (26 loc) · 944 Bytes
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
package modern.challenge;
import java.util.concurrent.locks.StampedLock;
public class ConvertToWriteLock {
private final StampedLock lock = new StampedLock();
private int balance = 1000;
public void withdraw(int amount) {
long stamp = lock.readLock();
try {
while (amount <= balance) {
long convertStamp = lock.tryConvertToWriteLock(stamp);
if (convertStamp != 0L) {
System.out.println("Lock successfully converted ...");
stamp = convertStamp;
balance = balance - amount;
System.out.println("New balance: " + balance);
break;
} else {
lock.unlockRead(stamp);
stamp = lock.writeLock();
}
}
} finally {
lock.unlock(stamp);
}
}
}