ReentrantReadWriteLock - many readers at a time, one writer at a time? ReentrantReadWriteLock - many readers at a time, one writer at a time? multithreading multithreading

ReentrantReadWriteLock - many readers at a time, one writer at a time?


Another way to achieve this (without using locks) is the copy-on-write pattern. It works well when you do not write often. The idea is to copy and replace the field itself. It may look like the following:

private volatile Map<String,HashMap> myStuff_ = new HashMap<String,HashMap>();public HashMap getter(String a) {    return myStuff_.get(a);}public synchronized void setter() {    // create a copy from the original    Map<String,HashMap> copy = new HashMap<String,HashMap>(myStuff_);    // populate the copy    // replace copy with the original    myStuff_ = copy;}

With this, the readers are fully concurrent, and the only penalty they pay is a volatile read on myStuff_ (which is very little). The writers are synchronized to ensure mutual exclusion.


Yes, if the write lock is held by a thread then other threads accessing the getter method would block since they cannot acquire the read lock. So you are fine here. For more details please read the JavaDoc of ReentrantReadWriteLock - http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html


You're kicking this thing off at the start of the day... you'll update it 0-2 times a day and you're reading it 100s of times per day. Assuming that the reading is going to take, say 1 full second(a looonnnng time) in an 8 hour day(28800 seconds) you've still got a very low read load. Looking at the docs for ReentrantReadWriteLock you can 'tweek' the mode so that it will be "fair", which means the thread that's been waiting the longest will get the lock. So if you set it to be fair, I don't think that your write thread(s) are going to be starved.

References

ReentrantReadWriteLock