Skip to content

Instantly share code, notes, and snippets.

@komamitsu
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komamitsu/c9d217512138b0744668 to your computer and use it in GitHub Desktop.
Save komamitsu/c9d217512138b0744668 to your computer and use it in GitHub Desktop.
static class ReentrantReadWriteLockExample {
private int loopNum = 30000;
private int slotNum = 10;
private int writeThreadNum = 5;
private int readThreadNum = 5;
public void examinReentrantReadWriteLock() throws InterruptedException {
final HashMap<Integer, Pair<Integer, Integer>> tbl = new HashMap<>();
for (int slot = 0; slot < slotNum; slot++) {
tbl.put(slot, new Pair<Integer, Integer>(0, 0));
}
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
ExecutorService executorService = Executors.newFixedThreadPool(writeThreadNum + readThreadNum);
final CountDownLatch countDownLatch = new CountDownLatch(writeThreadNum + readThreadNum);
Runnable writeTask = new Runnable() {
@Override
public void run() {
for (int i = 0; i < loopNum; i++) {
for (int slot = 0; slot < slotNum; slot++) {
ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
writeLock.lock();
Pair<Integer, Integer> pair = tbl.get(slot);
pair.first++;
pair.second++;
tbl.put(slot, pair);
writeLock.unlock();
}
}
System.out.println("writeTask: finished");
countDownLatch.countDown();
}
};
Runnable readTask = new Runnable() {
@Override
public void run() {
for (int i = 0; i < loopNum; i++) {
for (int slot = 0; slot < slotNum; slot++) {
ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
readLock.lock();
Pair<Integer, Integer> pair = tbl.get(slot);
int first = pair.first;
int second = pair.second;
if (first != second) {
System.out.println("values didn't match: slot=" + slot + ", first=" + first + ", second=" + second);
}
readLock.unlock();
}
}
System.out.println("readTask: finished");
countDownLatch.countDown();
}
};
for (int i = 0; i < writeThreadNum; i++) {
executorService.execute(writeTask);
}
for (int i = 0; i < readThreadNum; i++) {
executorService.execute(readTask);
}
long start = System.currentTimeMillis();
countDownLatch.await(30, TimeUnit.SECONDS);
System.out.println("elapsed time: " + (System.currentTimeMillis() - start));
for (int slot = 0; slot < slotNum; slot++) {
Pair<Integer, Integer> pair = tbl.get(slot);
System.out.println("slot=" + slot + ", expected=" + loopNum * writeThreadNum + ", first=" + pair.first + ", second=" + pair.second);
}
}
public void setLoopNum(int loopNum) {
this.loopNum = loopNum;
}
public void setSlotNum(int slotNum) {
this.slotNum = slotNum;
}
public void setWriteThreadNum(int writeThreadNum) {
this.writeThreadNum = writeThreadNum;
}
public void setReadThreadNum(int readThreadNum) {
this.readThreadNum = readThreadNum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment