-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReadWriteLock.java
113 lines (82 loc) · 2.79 KB
/
ReadWriteLock.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class Demo {
public static void main(String args[]) throws Exception {
final ReadWriteLock rwl = new ReadWriteLock();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Attempting to acquire write lock in t1: " + System.currentTimeMillis());
rwl.acquireWriteLock();
System.out.println("write lock acquired t1: " + +System.currentTimeMillis());
// Simulates write lock being held indefinitely
for (; ; ) {
Thread.sleep(500);
}
} catch (InterruptedException ie) {
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Attempting to acquire write lock in t2: " + System.currentTimeMillis());
rwl.acquireWriteLock();
System.out.println("write lock acquired t2: " + System.currentTimeMillis());
} catch (InterruptedException ie) {
}
}
});
Thread tReader1 = new Thread(new Runnable() {
@Override
public void run() {
try {
rwl.acquireReadLock();
System.out.println("Read lock acquired: " + System.currentTimeMillis());
} catch (InterruptedException ie) {
}
}
});
Thread tReader2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Read lock about to release: " + System.currentTimeMillis());
rwl.releaseReadLock();
System.out.println("Read lock released: " + System.currentTimeMillis());
}
});
tReader1.start();
t1.start();
Thread.sleep(3000);
tReader2.start();
Thread.sleep(1000);
t2.start();
tReader1.join();
tReader2.join();
t2.join();
}
}
class ReadWriteLock {
boolean isWriteLocked = false;
int readers = 0;
public synchronized void acquireReadLock() throws InterruptedException {
while (isWriteLocked) {
wait();
}
readers++;
}
public synchronized void releaseReadLock() {
readers--;
notify();
}
public synchronized void acquireWriteLock() throws InterruptedException {
while (isWriteLocked || readers != 0) {
wait();
}
isWriteLocked = true;
}
public synchronized void releaseWriteLock() {
isWriteLocked = false;
notify();
}
}