Java Concurrency Interview

Locks, conditions and AQS question 37 of 180 senior

When is ReentrantReadWriteLock a win, and when is it a trap?

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.

locks performance

Quiz yourself on Locks, conditions and AQS Suggest a correction