-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocksInJava.java
More file actions
161 lines (149 loc) · 5.66 KB
/
Copy pathLocksInJava.java
File metadata and controls
161 lines (149 loc) · 5.66 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package Phase7_Concurrency.Multithreading;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;
/**
* Locks in Java
* -------------
* Java offers TWO families of locking primitives:
* <p>
*
* 1. INTRINSIC LOCKS (a.k.a. monitor locks) — every Object has one.
* Used via `synchronized` blocks / methods and Object.wait/notify.
* Simple, baked into the language.
* <p>
*
* 2. EXPLICIT LOCKS — interfaces and classes in
* java.util.concurrent.locks. More features, more responsibilities.
* <p>
*
* The Lock Interface
* ------------------
* lock() - acquire, blocking
* lockInterruptibly() - acquire, interruptible
* tryLock() - return immediately; true if acquired
* tryLock(time, unit) - try up to a timeout
* unlock() - release
* newCondition() - associated condition variable
* <p>
*
* MUST be used with try/finally:
* <p>
*
* lock.lock();
* try { ... }
* finally { lock.unlock(); }
* <p>
*
* Implementations in this file
* ----------------------------
* ReentrantLock - the workhorse; reentrant; optional fairness;
* multiple Conditions; timed acquire.
* ReentrantReadWriteLock - separate read/write locks; many readers OR
* one writer.
* StampedLock - optimistic reads + write/read modes; not reentrant.
* <p>
*
* For dedicated files, see ReentrantLockDemo, ReadWriteLockDemo,
* StampedLockDemo.
* <p>
*
* Lock vs synchronized — quick comparison
* ---------------------------------------
* synchronized Lock
* --------------- ----------------
* Acquire timeout? No tryLock(time,unit)
* Interruptible acquire? No lockInterruptibly
* Fairness? No Optional in ReentrantLock
* Multiple conditions? No (one per object) Yes (newCondition)
* Auto-release on exit? Yes No — try/finally
* Hard to forget? Yes Easy to forget unlock
*/
public class LocksInJava {
public static void main(String[] args) throws InterruptedException {
section("1) ReentrantLock — basic acquire/release");
Lock lock = new ReentrantLock();
lock.lock();
try {
System.out.println("inside ReentrantLock critical section");
} finally {
lock.unlock();
}
section("2) ReentrantLock — tryLock with timeout");
Lock contended = new ReentrantLock();
Thread holder = new Thread(() -> {
contended.lock();
try { Thread.sleep(200); } catch (InterruptedException ignored) {}
finally { contended.unlock(); }
}, "holder");
holder.start();
Thread.sleep(30); // give holder a head start
boolean got = contended.tryLock(50, TimeUnit.MILLISECONDS);
System.out.println("tryLock(50ms) = " + got + " (expected false)");
if (got) contended.unlock();
holder.join();
section("3) ReentrantLock — interruptible acquire");
Lock notebook = new ReentrantLock();
Thread occupier = new Thread(() -> {
notebook.lock();
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
finally { notebook.unlock(); }
}, "occupier");
occupier.start();
Thread waiter = new Thread(() -> {
try {
notebook.lockInterruptibly();
System.out.println("waiter got the lock");
notebook.unlock();
} catch (InterruptedException ie) {
System.out.println("waiter interrupted before acquiring");
}
}, "waiter");
waiter.start();
Thread.sleep(30);
waiter.interrupt();
waiter.join();
occupier.join();
section("4) ReentrantLock — Condition variables");
Lock l = new ReentrantLock();
Condition cond = l.newCondition();
boolean[] ready = { false };
Thread w = new Thread(() -> {
l.lock();
try {
while (!ready[0]) cond.await();
System.out.println("w resumed");
} catch (InterruptedException ignored) {}
finally { l.unlock(); }
}, "w");
w.start();
Thread.sleep(30);
l.lock();
try { ready[0] = true; cond.signal(); }
finally { l.unlock(); }
w.join();
section("5) ReadWriteLock — many readers, one writer");
ReadWriteLock rw = new ReentrantReadWriteLock();
rw.readLock().lock();
try { System.out.println("reading"); }
finally { rw.readLock().unlock(); }
rw.writeLock().lock();
try { System.out.println("writing"); }
finally { rw.writeLock().unlock(); }
section("6) StampedLock — optimistic read");
StampedLock sl = new StampedLock();
long stamp = sl.tryOptimisticRead();
long x = 1, y = 2; // pretend these are guarded fields
if (!sl.validate(stamp)) {
// someone wrote during the optimistic read — re-read under a lock
stamp = sl.readLock();
try { /* re-read */ }
finally { sl.unlockRead(stamp); }
}
System.out.println("optimistic read x+y = " + (x + y));
section("done");
}
private static void section(String title) {
System.out.println();
System.out.println("=== " + title + " ===");
}
}