-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFairReadWriteLock.java
88 lines (68 loc) · 2.28 KB
/
FairReadWriteLock.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
//TESTING
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
public class FairReadWriteLock {
int numReaders=0; //number of readers at front of queue
int numWriters=0; //number of writers at front of queue
int nextTurn =0;
public int currentTurn = 0; // number of total threads in queue
ReentrantLock readerlock = new ReentrantLock();
ReentrantLock writerlock = new ReentrantLock();
/* READER = 0
* WRITER = 1
*/
//Reader blocked until all preceding writer
//threads acquire and release lock
public synchronized void beginRead() {
System.out.println("READER BEGIN: " + Thread.currentThread().getId());
int readTurn = currentTurn;
currentTurn++;
while(readTurn!=nextTurn || numWriters > 0 ){
try {
// System.out.println("READER BLOCKED: " + Thread.currentThread().getId());
wait();
// System.out.println("READER UNBLOCKED: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//number of readers at front of the queue
//(unblocked reader)
numReaders ++;
}
public synchronized void endRead() {
System.out.println("READER LEAVES: " + Thread.currentThread().getId());
nextTurn ++;
numReaders--;
notifyAll(); //condition changed, notify
}
//blocked until all preceding reader and
//writer threads have acquired and released lock
public synchronized void beginWrite() {
System.out.println("WRITER BEGIN: " + Thread.currentThread().getId());
int writeTurn = currentTurn;
currentTurn++;
while(writeTurn != nextTurn || numReaders > 0 || numWriters > 0 ){
/********WAIT CALL*********/
try {
// System.out.println("WRITER BLOCKED: " + Thread.currentThread().getId());
this.wait();
// System.out.println("WRITER UNBLOCKED: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
/**************************/
}
//Only increment when the writer is not blocked
// (it is at front of queue)
numWriters++;
}
public synchronized void endWrite() {
System.out.println("WRITER LEAVES: " + Thread.currentThread().getId());
nextTurn++;
numWriters--;
notifyAll(); //condition changed, notify
}
}