Rob Prime wrote:What you want is a read-many-write-one lock: reading threads can have access unless another thread is writing; other reading threads are not a problem. Writing threads must wait until all other reading and writing threads have finished. don't know if this has been implemented in Java yet but it's not that hard to implement yourself if it isn't.
Further to Rob comments( thanks Rob). There is in java 5 ( concurrency util) something called ReadWriteLock.
If we look at the JAVA
DOC; it says:
"A ReadWriteLock maintains a pair of associated Lock locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
All ReadWriteLock implementations must guarantee that the memory synchronization effects of writeLock operations (as specified in the Lock interface) also hold with respect to the associated readLock. That is, a thread successfully acquiring the read lock will see all updates made upon previous release of the write lock. "
Now the last statement is very interesting which means there will be no stale data so any read thread will capture the latest write thread so this is a guranttee of visibility across all reader threads.
Now if we compare the performance of ReadWriteLock implementation ( ReentrantReadWriteLock) w.r.t. ReentrantLock; we can see on the average for more then 4 threads we will get almost double throughput ( measure of taks compleleted per
unit of time)
Now if we give an example here to clarify the concept more; please notice, I am assuming you are using java 5 and above.
I hope this could help