It should be noted that StampedLock
has since come out with Java 8, and it's much faster than ReentrantReadWriteLock
(especially as you use more and more threads) when you don't use the lock in a reentrant manner (using StampedLock
reentrantly can lead to deadlocks, so don't do it).
It also allows optimistic read nonlocks that are available if there is no write lock in effect. Unlike a normal read lock, they don't block a write lock from being established. You can check whether a write lock has been established over your optimistic read nonlock by using the validate
method.
Its interface is a little different since you have to store a long
value called a stamp in order to later unlock a read or write lock properly or to later validate
an optimistic read nonlock properly when you're done.