-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReaderWriter.java
More file actions
67 lines (61 loc) · 2.07 KB
/
ReaderWriter.java
File metadata and controls
67 lines (61 loc) · 2.07 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
/**
* The ReaderWriter class represents a simple implementation of a reader-writer problem.
* It allows multiple readers to read data concurrently, while ensuring that only one writer can write data at a time,
* and no reader can read while there is an active writer.
**/
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReaderWriter implements ReadWriteInterface {
private String data;
private int readersCount;
private Lock writerLock;
private Lock readersLock;
public ReaderWriter() {
this.data = "";
this.readersCount = 0;
this.writerLock = new ReentrantLock();
this.readersLock = new ReentrantLock();
}
// Rread Data Function
public void readData(int readerId) {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000) + 1000);
System.out.println("** Reader " + readerId + " is reading data. " + this.data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Write Data Function
public void writeData(int writerId) {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000) + 1000);
String new_data = "** New data written by Writer " + writerId;
this.data = new_data;
System.out.println("** Writer " + writerId + " has written data. " + new_data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void startReading(int readerId) {
readersLock.lock();
if (readersCount == 0) {
writerLock.lock();
}
readersCount++;
readersLock.unlock();
readData(readerId);
readersLock.lock();
readersCount--;
if (readersCount == 0) {
writerLock.unlock();
}
readersLock.unlock();
}
public void startWriting(int writerId) {
writerLock.lock();
writeData(writerId);
writerLock.unlock();
}
}