-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathUsingExplicitReadWriteLocks.java
89 lines (81 loc) · 2.41 KB
/
UsingExplicitReadWriteLocks.java
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package br.com.leonardoz.features.locks;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
/**
*
* Special lock with a different strategy: allow multiple readers simultaneously
* and only one single writer.
*
* ReadLock readLock = rwLock.readLock();
*
* WriteLock writeLock = rwLock.writeLock();
*
* Read access is granted if there's no Writer or a Writer requesting access.
*
* Write access is granted if there's no Reader.
*
* ReentrantReadWriterLock gives reentrant capabilities do ReadWriteLock
*
* Fair in constructor:
*
* true: Fair Lock, newly requesting threads are queued if the lock is held.
*
* false: Unfair lock: if the lock is held, requesting threads can 'jump' the
* waiting queue (default, specially for write lock).
*
*/
public class UsingExplicitReadWriteLocks {
// Equivalent to Intrinsic Locks
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private String myContent = "A long default content......";
/**
* Simplest way to use the read mode
*
* @return
*/
public String showContent() {
ReadLock readLock = readWriteLock.readLock();
readLock.lock();
try {
System.out.println("Reading state while holding a lock.");
return myContent;
} finally {
readLock.unlock();
}
}
public void writeContent(String newContentToAppend) {
WriteLock writeLock = readWriteLock.writeLock();
writeLock.lock();
try {
System.err.println("Writing " + newContentToAppend);
myContent = new StringBuilder().append(myContent).append(newContentToAppend).toString();
} finally {
writeLock.unlock();
}
}
public static void main(String[] args) {
var executor = Executors.newCachedThreadPool();
var self = new UsingExplicitReadWriteLocks();
// Readers
for (int i = 0; i < 100; i++) {
executor.submit(() -> {
try {
// Delay readers to start
Thread.sleep(new Random().nextInt(10) * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(self.showContent());
});
}
// Writers - only if no writer is available
for (int i = 0; i < 5; i++) {
executor.execute(() -> self.writeContent(UUID.randomUUID().toString()));
}
executor.shutdown();
}
}