-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadWriteLockDemo.java
More file actions
146 lines (133 loc) · 5.26 KB
/
Copy pathReadWriteLockDemo.java
File metadata and controls
146 lines (133 loc) · 5.26 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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package Phase7_Concurrency.Multithreading;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* java.util.concurrent.locks.ReadWriteLock
* ----------------------------------------
* Two locks for the price of one:
* <p>
*
* READ LOCK - many threads may hold it simultaneously.
* WRITE LOCK - exclusive; no readers or writers can be active.
* <p>
*
* Use when reads VASTLY OUTNUMBER writes — a configuration cache,
* lookup table, in-memory index.
* <p>
*
* The canonical implementation
* ----------------------------
* ReadWriteLock rw = new ReentrantReadWriteLock();
* Lock r = rw.readLock();
* Lock w = rw.writeLock();
* <p>
*
* r.lock(); try { ...read... } finally { r.unlock(); }
* w.lock(); try { ...write... } finally { w.unlock(); }
* <p>
*
* Important properties
* --------------------
* - REENTRANT — a thread holding the write lock can also acquire the
* read lock and vice versa for downgrading.
* - LOCK DOWNGRADING is allowed (write → read).
* - LOCK UPGRADING is NOT (read → write would deadlock if multiple
* readers tried). Release the read lock first.
* - FAIR option behaves like ReentrantLock's.
* - Both locks share a single CONDITION namespace — only the WRITE
* lock can produce Conditions.
* <p>
*
* Pitfalls
* --------
* 1. Write starvation. Under heavy read load, writers may wait
* forever. Use a FAIR ReentrantReadWriteLock if that's a risk.
* 2. Overhead. The bookkeeping is more expensive than a single lock.
* For tiny critical sections you can lose throughput.
* 3. Consider StampedLock or ConcurrentHashMap as alternatives.
*/
public class ReadWriteLockDemo {
/** Tiny thread-safe map with read/write split. */
static class RwMap<K, V> {
private final ReadWriteLock rw = new ReentrantReadWriteLock();
private final Lock r = rw.readLock();
private final Lock w = rw.writeLock();
private final Map<K, V> data = new HashMap<>();
public V get(K key) {
r.lock();
try { return data.get(key); }
finally { r.unlock(); }
}
public void put(K key, V value) {
w.lock();
try { data.put(key, value); }
finally { w.unlock(); }
}
public int size() {
r.lock();
try { return data.size(); }
finally { r.unlock(); }
}
}
public static void main(String[] args) throws InterruptedException {
section("1) Many readers run concurrently, one writer is exclusive");
RwMap<String, Integer> map = new RwMap<>();
for (int i = 0; i < 5; i++) map.put("k" + i, i);
// 4 readers, 1 writer
Thread[] readers = new Thread[4];
for (int i = 0; i < readers.length; i++) {
final int id = i;
readers[i] = new Thread(() -> {
for (int k = 0; k < 5; k++) {
Integer v = map.get("k" + (k % 5));
System.out.println(" reader " + id + " saw k" + (k%5) + "=" + v);
try { Thread.sleep(20); } catch (InterruptedException ignored) {}
}
}, "reader-" + i);
}
Thread writer = new Thread(() -> {
for (int i = 0; i < 3; i++) {
map.put("k" + i, i + 100);
System.out.println(" writer updated k" + i);
try { Thread.sleep(40); } catch (InterruptedException ignored) {}
}
}, "writer");
for (Thread t : readers) t.start();
writer.start();
for (Thread t : readers) t.join();
writer.join();
section("2) Lock downgrade — write lock then acquire read lock then release write");
ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
rw.writeLock().lock();
try {
// do write
rw.readLock().lock(); // downgrade — still own write
rw.writeLock().unlock(); // release write, keep read
try {
System.out.println("now reading under read lock; can't upgrade back to write");
} finally {
rw.readLock().unlock();
}
} catch (Throwable t) {
// if anything went wrong before the explicit unlock above
if (rw.isWriteLockedByCurrentThread()) rw.writeLock().unlock();
}
section("3) DO NOT try to upgrade — would deadlock");
// rw.readLock().lock();
// rw.writeLock().lock(); // <-- this thread is also a reader; ANOTHER
// // reader prevents the write lock acquire.
section("4) Fair vs unfair under contention");
ReentrantReadWriteLock fair = new ReentrantReadWriteLock(true);
// In a fair rwlock, a queued writer prevents new readers from
// jumping ahead of it. Helps writer-starvation but slower.
System.out.println("fair = " + fair.isFair());
section("done");
}
private static void section(String title) {
System.out.println();
System.out.println("=== " + title + " ===");
}
}