Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 893897a

Browse files
add ReentrantReadWriteLock on shared state (#13)
1 parent 3260d2f commit 893897a

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

‎Concurrency/SharedState.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import java.util.concurrent.locks.ReadWriteLock;
2+
import java.util.concurrent.locks.ReentrantReadWriteLock;
3+
4+
public class SharedState {
5+
// shared resource
6+
private volatile int data;
7+
// lock for the resource
8+
ReadWriteLock rwLock = new ReentrantReadWriteLock();
9+
10+
private static final int READ_CYCLES = (int)1e8;
11+
private static final int WRITE_CYCLES = (int)1e8;
12+
13+
public SharedState(int initialData) {
14+
this.data = initialData;
15+
}
16+
17+
/**
18+
* Retrieves the data from a private static variable.
19+
* Representing a shared resource
20+
*
21+
* @return The data value stored
22+
*/
23+
private int getData() {
24+
rwLock.readLock().lock();
25+
try {
26+
return data;
27+
} finally {
28+
rwLock.readLock().unlock();
29+
}
30+
}
31+
32+
/**
33+
* Updates the value of the private static variable 'data'.
34+
*/
35+
private void updateData() {
36+
rwLock.writeLock().lock();
37+
try {
38+
data += 1;
39+
} finally {
40+
rwLock.writeLock().unlock();
41+
}
42+
43+
}
44+
45+
public static void main(String ...args) throws InterruptedException {
46+
final long startTime = System.nanoTime();
47+
SharedState sharedState = new SharedState(0);
48+
Thread readerThread = new Thread(new Runnable() {
49+
@Override
50+
public void run() {
51+
for(int cycles = 0; cycles < READ_CYCLES; cycles++) {
52+
int value = sharedState.getData();
53+
// to keep I/O low to influence perf
54+
if(cycles % (READ_CYCLES/10) == 0){
55+
System.out.println("read: " + value);
56+
System.out.flush();
57+
}
58+
}
59+
}
60+
});
61+
Thread writerThread = new Thread(new Runnable() {
62+
@Override
63+
public void run() {
64+
for(int cycles = 0; cycles < WRITE_CYCLES; cycles++) {
65+
sharedState.updateData();
66+
int value = sharedState.getData();
67+
if(cycles % (WRITE_CYCLES/10) == 0){
68+
System.out.println("post write: " + value);
69+
System.out.flush();
70+
}
71+
}
72+
}
73+
});
74+
readerThread.start();
75+
writerThread.start();
76+
readerThread.join();
77+
writerThread.join();
78+
final long duration = System.nanoTime() - startTime;
79+
System.out.println("time taken(ns): " + duration);
80+
}
81+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /