Locks, conditions and AQS question 37 of 180 senior
When is ReentrantReadWriteLock a win, and when is it a trap?
- Always a win, reads are more common than writes
- Correct: A win for long reads and rare writes; a loss for short critical sections, where its bookkeeping costs more than the exclusion it avoids
- It allows several writers as long as they touch different fields
- It upgrades a read lock to a write lock automatically
Read/write locks pay off when reads dominate and each critical section is long enough for the
parallelism to be worth the extra bookkeeping. Every acquisition has to update a shared counter, which
is itself a contended write, so for a two-field getter a plain ReentrantLock usually wins.
Three traps worth naming. Upgrading a read lock to a write lock is not supported and deadlocks the thread against itself; you must release and reacquire, and recheck your state. Under a steady stream of readers a non-fair write lock can be starved. And a reader that blocks on I/O holds the lock and blocks every writer behind it.
StampedLock exists because of this, and immutable snapshots or CopyOnWriteArrayList often beat both.
Quiz yourself on Locks, conditions and AQS Suggest a correction