-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCovertToWriteLock.java
More file actions
46 lines (39 loc) · 1.14 KB
/
CovertToWriteLock.java
File metadata and controls
46 lines (39 loc) · 1.14 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
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;
public class CovertToWriteLock extends ConcurrentUtils {
static int count = 0;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
StampedLock lock = new StampedLock();
executor.submit(() ->
{
long stamp = lock.readLock();
try {
if (count == 0) {
//when count 0, write count so change writeLock
/*
* convert a read lock into a write lock without unlocking
* and locking again.
* tryConvertToWriteLock doesn't block
* but may return a zero stamp indicating that
* no write lock is currently available.
*
* tryConvertToWriteLock should unlock the readLock
*/
stamp = lock.tryConvertToWriteLock(stamp);
if (stamp == 0L) {
System.out
.println("Could not convert to write lock");
stamp = lock.writeLock();
}
count = 23;
}
System.out.println(count);
} finally {
lock.unlock(stamp);
}
});
stop(executor);
}
}