-
Notifications
You must be signed in to change notification settings - Fork 20
/
SimpleReadWriteLock.java
102 lines (87 loc) · 2.37 KB
/
SimpleReadWriteLock.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
package com.github.mottox.taomp.concurrent.locks;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 简单的读写锁实现。
*/
public class SimpleReadWriteLock implements ReadWriteLock {
private volatile int readers;
private volatile boolean writer;
private Lock lock;
private Condition condition;
private SimpleLock readLock;
private SimpleLock writeLock;
public SimpleReadWriteLock() {
this.readers = 0;
this.writer = false;
this.lock = new ReentrantLock();
this.readLock = new ReadLock();
this.writeLock = new WriteLock();
this.condition = lock.newCondition();
}
@Override
public Lock readLock() {
return readLock;
}
@Override
public Lock writeLock() {
return writeLock;
}
private class ReadLock implements SimpleLock {
@Override
public void lock() {
lock.lock();
try {
while (writer) {
condition.await();
}
readers++;
} catch (InterruptedException e) {
// empty
} finally {
lock.unlock();
}
}
@Override
public void unlock() {
lock.lock();
try {
readers--;
if (readers == 0) {
condition.signalAll();
}
} finally {
lock.unlock();
}
}
}
private class WriteLock implements SimpleLock {
@Override
public void lock() {
lock.lock();
try {
while (readers > 0 || writer) {
condition.await();
}
writer = true;
} catch (InterruptedException e) {
// empty
} finally {
lock.unlock();
}
}
@Override
public void unlock() {
// 原书上这里需要获取lock,个人认为可以不需要。
lock.lock();
try {
writer = false;
condition.signalAll();
} finally {
lock.unlock();
}
}
}
}