Lesson · Multithreading Fundamentals
Locks: ReentrantLock, ReadWriteLock, StampedLock and the Condition
17 min readLocks
A monitor is unfair, uninterruptible and has a single wait set. A Lock is what you take when that is not enough: tryLock for bounded waits, lockInterruptibly for cancellation, a fairness option, several Conditions on one lock, a read/write split for read-mostly data, and StampedLock's optimistic reads for the hottest of those. All of them share one engine underneath.
What the monitor cannot do
A monitor is a lock plus a wait set, and it is unfair, uninterruptible and all or nothing: synchronized either gets the thread in or parks it until the owner leaves. That covers most code, which is why it is still the default.
The exceptions arrive as product requirements rather than style preferences. Give up after 200 milliseconds instead of hanging. Cancel a wait when the user closes the request. Wake exactly the producers when a slot frees. Let ten readers through while no writer is active. Each one is a monitor feature that does not exist.
java.util.concurrent.locks supplies each of those as an object you can hold, configure and pass around. The classes differ in features, and they share the machinery, so learning one teaches the shape of all of them.
- A bounded wait:
tryLock()answers immediately;tryLock(timeout, unit)waits with a deadline. - A cancellable wait:
lockInterruptibly()throwsInterruptedExceptioninstead of parking forever. - Targeted wake-ups:
newCondition()creates separate wait sets, sosignal()can wake one kind of waiter. - Read-mostly access:
ReentrantReadWriteLockandStampedLocklet readers share while no writer is active. - Deterministic turns: the fair constructor hands the lock over in arrival order instead of letting newcomers barge in.
synchronized is the default; a Lock is for timeout, interruption, fairness or multiple wait sets. If you need none of those, the monitor is less code and fewer ways to be wrong.
ReentrantLock: the acquisition menu
ReentrantLock is the monitor in object form. The thread that holds it can lock it again, the hold count is tracked, and the same thread must unlock it as many times as it locked. Reentrancy and ownership match synchronized; only the waiting is configurable.
Each acquisition method answers a different question about waiting. lock() waits with no exit. tryLock() refuses to wait at all. tryLock(timeout, unit) waits with a deadline. lockInterruptibly() waits until the lock is free or the thread is interrupted. Only the last two can be cut short, and the first one is the method every tutorial shows.
| Call | Waits | Interruptible | Use it when |
|---|---|---|---|
lock() | until free | no | plain mutual exclusion is all you need |
tryLock() | never, one attempt | n/a | the caller can do something else instead of queueing |
tryLock(timeout, unit) | up to the deadline | yes | worst-case latency must be bounded |
lockInterruptibly() | until free or interrupted | yes | cancellation must reach a waiting thread |
unlock() | n/a | n/a | in a finally, in the same method that locked |
- Call
tryLock(). True means the lock is yours: enter atryblock and unlock infinally. - False means someone else is inside. Do not queue: back off (sleep a short, growing interval) and try again, or take another path.
- Bound the attempts. When the budget runs out, fail loudly or fall back to a blocking lock, because an unbounded retry loop is a busy queue with extra steps.
unlock() belongs in a finally, in the same method that locked. A Lock does not release when the method exits, and a lock left held blocks every later caller.
Lock scenario lab
pick a scenarioA bounded wait instead of a queue
T1: lock.lock(); // holds it: slow work inside
T2: lock.tryLock(200, MILLISECONDS); // waits at most 200ms
T2: if (!got) { shedLoad(); } // what runs when the deadline passes
lock() would have parked T2 with no exit; a bounded tryLock turns contention into a decision.
accent = thread 1 · violet = thread 2 · amber = blocked or lost · emerald = resolved
Condition: many wait sets on one lock
An object monitor has exactly one wait set, so a producer and a consumer parked on the same monitor cannot be told apart. notifyAll() wakes both kinds, and the ones whose state is still wrong go straight back to sleep. Correct, and noisy.
lock.newCondition() creates an independent wait set. await releases the lock and parks the thread in that set; signal wakes one thread in the set, signalAll wakes all of them, and the scheduler is only allowed to pick from the named set.
The protocol keeps the rules of wait/notify and adds one: await and signal must run while holding the lock. Outside it they throw IllegalMonitorStateException, which is the API refusing to guess which lock you meant.
- await() releases the lock while waiting and re-acquires it before returning, so the thread it waits for can actually make progress.
- Re-check in a while loop: a wake-up is permission to re-test the guard, not proof that the condition holds.
- Signal the set that can act: a freed slot wakes one producer with
notFull.signal()and leaves the consumers parked. - Timeouts and uncancellable waits exist too:
await(timeout, unit)bounds the wait,awaitUninterruptibly()refuses to be cut short.
One monitor has one wait set; one lock can have as many Conditions as the states your invariant needs.
ReentrantReadWriteLock: many readers, or one writer
A read/write lock separates the two kinds of access: any number of readers hold the read lock together, while a writer needs the place to itself. The deal pays off when reads dominate and overlap, and it loses its advantage when writes are dense.
ReentrantReadWriteLock is reentrant in both modes and accepts the same fairness flag as ReentrantLock. The asymmetry to memorise: no upgrade, but downgrade works. Holding the write lock and taking the read lock before releasing the write lock is legal; holding the read lock and asking for the write lock waits for every reader to leave, and you are one of them.
The other hazard lives in the default non-fair mode: a steady stream of arriving readers can keep the read lock busy and leave a writer parked indefinitely. Fair mode queues newcomers behind the waiting writer instead, and pays for it in throughput.
- Acquire the write lock.
- Mutate the shared state, so no other thread can observe a half-updated version.
- Acquire the read lock while still holding the write lock. This is the downgrade, and it is supported.
- Release the write lock. Other readers may now join, and you keep reading a state you know is consistent.
- Release the read lock last.
Read then write deadlocks; write then read is the supported direction. Choose lock modes in an order that only ever downgrades.
StampedLock: the optimistic read
StampedLock (Java 8) adds a third mode: the optimistic read. tryOptimisticRead() returns a stamp without touching the lock state at all. The reader copies the fields into locals, then validate(stamp) reports whether a writer has moved in since the stamp was issued.
If validation passes, the read is complete, and it never blocked, never queued and never allocated. If it fails, the locals may hold a torn view, so they are thrown away and the read is retried under a real read lock. Losing the bet costs one retry.
The restrictions are the price: no reentrancy (a second acquisition can deadlock even on the same thread), no interruptible acquisition, and no Conditions. It is a specialist for read-mostly data, and it should be the last lock you reach for, not the first.
long stamp = lock.tryOptimisticRead(); // no lock state touched, nothing can block double x = px, y = py; // copy into locals: the read is now a candidate if (!lock.validate(stamp)) { // a writer ran: the locals may be inconsistent stamp = lock.readLock(); // pay for a real lock and read again try { x = px; y = py; } finally { lock.unlockRead(stamp); // every mode has its own unlock } }
An optimistic read is a bet that no writer is active; validate() is how you find out you lost. Never use the shared fields after a failed validation, and never store a stamp for later.
Choosing between them
The tools form a ladder. Start with synchronized, and step down only when you can name the feature you need: a timeout, an interruptible wait, fairness, several wait sets, or reader sharing. Stepping down without a reason buys complexity and a new class of bug.
The table below is that decision written out, and the map that follows it closes the match from a named gap to a tool.
| Tool | What it adds | What it costs you |
|---|---|---|
synchronized | mutual exclusion and one wait set, released by the JVM | no timeout, no interruptible wait, one wait set, no fairness |
ReentrantLock | tryLock, lockInterruptibly, fair mode, many Conditions | unlock() is your job on every path |
ReentrantReadWriteLock | readers share, a writer is exclusive, downgrade, fair mode | no upgrade; writer starvation without fairness; more overhead than plain exclusion |
StampedLock | optimistic reads that never block | not reentrant, no interruptible lock acquisition, no Conditions |
Reach for a Lock when you can name the monitor feature you are missing; otherwise synchronized is less code and fewer ways to be wrong.
Decision map · locks
start at the monitor; take a tool only for a named gapsynchronized
the default: one lock, one wait set, no options
What does the monitor lack?
A bounded wait instead of a queue
A wait the caller can cancel
Separate wait sets on one lock
Readers share, a writer is alone
Reads too hot to block
Turns in arrival order
Inset · one lock, two wait sets
newCondition(), twice
await() parks a thread in the named set; signal() wakes one thread from that set. A monitor has a single set for both kinds of waiter, which is why it falls back to notifyAll().
Underneath: one engine, many front doors
These classes do not each implement their own waiting room. They delegate to AbstractQueuedSynchronizer (AQS): one int of state plus a FIFO queue of parked threads. A ReentrantLock stores its hold count in that int, ReentrantReadWriteLock splits it into reader and writer halves, and a Semaphore stores permits.
When an acquisition cannot proceed, the thread becomes a node in the queue and is parked with LockSupport.park(). Every release unparks the next eligible node, so the wake-up path is the same machinery in every class. Fair mode is a single extra rule: check the queue before letting a new arrival barge in front of it.
Conditions plug into the same engine. Each Condition owns its own queue, and signal moves one node from the condition queue to the lock queue. One implementation explains the behaviour of all of them, including the fairness flag and interruptible waits.
State plus a FIFO queue plus park/unpark: learn AQS once and every lock in java.util.concurrent reads the same way.
What to remember
The rules worth keeping:
- synchronized is the default: a Lock is for timeout, interruption, fairness or multiple wait sets.
- Every acquisition needs a release path: unlock() in a finally, in the same method that locked.
- Conditions are wait sets: hold the lock to await and to signal, re-check the guard in a while loop, and signal the set that can make progress.
- Read/write locks never upgrade: downgrade in one direction, or take the write lock for the whole operation.
- StampedLock is the specialist: optimistic reads for read-mostly data, with no reentrancy, interruption or Conditions to fall back on.
A lock is a liability you add to the code: every Lock should be justified by a feature, and every acquisition needs a release path you can point to.
Read, then write, and wait forever
ReentrantReadWriteLock supports the downgrade (hold write, take read, drop write) and refuses the upgrade. A thread holding the read lock that asks for the write lock waits for every reader to leave, and it is one of them, so the wait never ends. If a read-modify-write needs both modes, take the write lock for the whole sequence, or read, release, and re-validate under the write lock.
Interview angles
When would you reach for ReentrantLock over synchronized?+
Only for a feature the monitor lacks: tryLock with a timeout, lockInterruptibly for cancellation, the fair constructor, multiple Conditions on one lock, or a read/write split. Otherwise synchronized is less code and cannot leak a lock.
lock() itself is not interruptible. Only lockInterruptibly() and tryLock(timeout, unit) respond to an interrupt while waiting; plain lock() ignores it until the lock is free.
What does tryLock() give you that lock() cannot?+
A decision. tryLock() returns false immediately instead of queueing, and tryLock(timeout, unit) gives up at a deadline. A caller can shed load, retry with backoff, or dodge a lock-ordering deadlock instead of blocking.
The classic shape is two locks in opposite orders: acquire A, then tryLock B. When B is not free, release A and retry with backoff. A blocking pair of acquisitions would have deadlocked.
Common misconception: tryLock() spins until it succeeds.
Why do Condition objects beat a monitor's wait set?+
One monitor has one wait set, so notifyAll() wakes producers and consumers together and most of them re-check and go back to sleep. Each Condition is its own wait set, so a freed slot can wake exactly one producer while the consumers keep sleeping.
Condition.await() releases the lock while waiting and re-acquires it before returning, exactly like Object.wait(). The guard stays a while loop because wake-ups can be spurious or arrive before the state is right.
Can you upgrade the read lock to the write lock in ReentrantReadWriteLock?+
No. Holding the read lock and acquiring the write lock deadlocks, because your own read hold is part of what the writer must wait for. Downgrade works in the other direction: take the write lock, acquire the read lock, then release the write lock while you keep reading.
Common misconception: Reentrancy covers both directions.
Follow-up: How do you perform a read-modify-write safely, then?
What does StampedLock's optimistic read buy, and what do you give up?+
tryOptimisticRead() takes a stamp without touching the lock state, and validate(stamp) checks that no writer intervened, so uncontended reads never block or allocate. You give up reentrancy, interruptible acquisition and Conditions.
The pattern is read into locals, validate, and retry under readLock() when validation fails. The stamp is meant to be held for the duration of one read, never stored: staleness is the entire signal.
What is AQS, and why does it matter that these locks share it?+
AbstractQueuedSynchronizer is the engine: one int of state plus a FIFO queue of parked threads (LockSupport.park/unpark). ReentrantLock, ReentrantReadWriteLock, Semaphore and CountDownLatch all delegate to it, which is why fairness and interruptible waits behave the same way across all of them.