Java Reference ยท Concurrency
ReadWriteLock and StampedLock
Reference for ReentrantReadWriteLock and StampedLock: shared read locks, exclusive write locks, downgrading, optimistic reads and why upgrading deadlocks.
When data is read far more often than it is written, a plain lock is wasteful: readers block each other even though they cannot interfere. A read-write lock allows many readers at the same time but gives a writer exclusive access. Java provides two: ReentrantReadWriteLock (implementing the ReadWriteLock interface) and the newer, lower-level StampedLock, which adds an optimistic read that takes no lock at all.
Both pay off only when reads dominate and the read section is long enough to matter. For short sections, an ordinary synchronized block or ReentrantLock is often just as fast and much simpler.
ReadWriteLock rw = new ReentrantReadWriteLock(); rw.readLock().lock(); // many threads can hold this at once rw.writeLock().lock(); // exclusive: no readers, no other writers
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface ReadWriteLock { Lock readLock(); Lock writeLock(); } public class ReentrantReadWriteLock implements ReadWriteLock public class StampedLock implements java.io.Serializable
ReentrantReadWriteLock member |
Description |
|---|---|
readLock(), writeLock() |
Return Lock objects (lock, tryLock, unlock, and so on). |
new ReentrantReadWriteLock(boolean fair) |
Optional fair ordering; default is unfair. |
getReadLockCount(), getReadHoldCount(), isWriteLocked() |
Monitoring. |
writeLock().newCondition() |
Conditions are supported for the write lock only. |
StampedLock method |
Description |
|---|---|
long tryOptimisticRead() |
Returns a stamp, or 0 if the write lock is held. Takes no lock. |
boolean validate(long stamp) |
true if no write lock was acquired since the stamp was issued. |
long readLock(), writeLock() |
Blocking acquisition; return a stamp used to unlock. |
unlockRead(stamp), unlockWrite(stamp), unlock(stamp) |
Release by stamp. |
long tryConvertToWriteLock(long stamp) |
Converts an optimistic or read stamp into a write stamp; returns 0 if impossible. |
Usage notes
- No upgrade in
ReentrantReadWriteLock. A thread holding the read lock that callswriteLock().lock()blocks forever, waiting for itself. Release the read lock first and re-check the data after taking the write lock. - Downgrading is supported: acquire the read lock before releasing the write lock, as the example shows.
- Writer starvation. The default policy can let a steady stream of readers delay a writer. A fair lock reduces that at a cost in throughput.
StampedLockis not reentrant and has noConditions. Locking it twice in one thread deadlocks. Stamps must be passed back to the matching unlock method.- Optimistic reads must be copied. Read the fields into local variables, validate, and only then use the locals. If validation fails, retry under a real read lock.
StampedLockignores thread ownership, so a stamp can be released by another thread. That flexibility is also a source of bugs.- Measure first. Read-write locks have more overhead than a simple lock, and
ConcurrentHashMap,CopyOnWriteArrayListor an immutable snapshot often solve the same problem better. - Memory visibility works like other locks: releasing the write lock happens-before later acquisitions.