-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRwlDowngradeDemo.java
More file actions
41 lines (36 loc) · 1.38 KB
/
Copy pathRwlDowngradeDemo.java
File metadata and controls
41 lines (36 loc) · 1.38 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.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RwlDowngradeDemo{
public static volatile boolean writable = false;
public static void main(String[] args){
ReadWriteLock rwl = new ReentrantReadWriteLock();
ExecutorService es = Executors.newFixedThreadPool(5);
es.submit(new Runnable(){
public void run(){
try{
rwl.writeLock().lock();
if(writable){
System.out.println(Thread.currentThread() + " Writing something, " + "with " + rwl.writeLock());
writable = true;
}else{
// read
rwl.readLock().lock();
System.out.println(Thread.currentThread() + " Reading something, " + "with " + rwl.readLock());
}
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println(rwl.writeLock() + ", " + rwl.readLock());
rwl.writeLock().unlock();
System.out.println("WriteLock released: \n" + rwl.writeLock() + ", " + rwl.readLock());
rwl.readLock().unlock();
System.out.println("ReadLock released: \n" + rwl.writeLock() + ", " + rwl.readLock());
}
es.shutdown(); // If you want the application end, you need to call the shutdown method otherwise it will be waiting for new runnables.
}
});
}
}