Lesson · Executors, Thread Pools & Async Programming
Synchronizers: latches, barriers, semaphores and phasers
16 min readSynchronizers
wait/notify can express every coordination pattern, and hand-rolling them is how coordination bugs are born. CountDownLatch, CyclicBarrier, Semaphore, Phaser and Exchanger are those patterns packaged and tested, each with one job and one sharp edge.
Coordination is a different job from mutual exclusion
A lock answers one question: who may run this code right now. Most of the interesting waits in a concurrent program are not that question. A startup path waits for N services to report ready. A simulation holds every worker at the end of each round. A client keeps at most eight requests in flight.
Every one of those can be built on wait/notify, and the wait-notify lesson showed the protocol in full: hold the monitor, test the condition, wait in a loop, re-check. The trouble is everything around the protocol. Each team re-derives the counters, the generation numbers and the timeouts, and each team gets a different subset right.
The synchronizers in java.util.concurrent are those protocols, packaged: five tools, five shapes of waiting. Reaching for the wrong one still compiles and still wakes threads, which is why the bug survives review for weeks.
- Many waiters wait for one event, or one waits for many events: CountDownLatch.
- N parties wait for each other, round after round: CyclicBarrier.
- A counted pool of capacity: Semaphore.
- A changing set of parties across phases: Phaser.
- Exactly two threads swap values: Exchanger.
Mutual exclusion asks who may run; a synchronizer asks who must wait. Keep the two questions apart and the right tool is usually obvious.
The family portrait
The five tools differ along three axes: who does the waiting, whether the tool can be used more than once, and where the count comes from. Everything else (fairness, timeouts, interruption) is a refinement of one of those.
Read the table from left to right and the choice usually makes itself: a one-shot wait is a latch, a repeated rendezvous is a barrier, a cap on in-flight work is a semaphore, a changing set of parties is a phaser, and a swap between two threads is an exchanger.
| Tool | Coordinates | Reusable | Parties | Typical use |
|---|---|---|---|---|
| CountDownLatch | waiters wait for N events | no, one shot | counts down to zero | start gate, done gate |
| CyclicBarrier | N parties wait for each other | yes, per generation | fixed at construction | round-based work: simulation steps, batch phases |
| Semaphore | at most N holders at once | yes | counts permits, no identity | capping parallel calls, pooling resources |
| Phaser | N parties wait, phase after phase | yes, many phases | changes at run time | multi-stage work where threads join and leave |
| Exchanger | two threads swap values | yes, per call | exactly two | pipeline handoff, double buffering |
Pick by the shape of the waiting, not by the closest API name. The wrong synchronizer will happily wait for the wrong event.
synchronizers · five shapes of waiting
every tool here exists because one shape kept being re-implemented by hand
Counts down to zero, releases every waiter, and records nothing else. No reset method.
Start gate: N waiters, one countDown. Done gate: one waiter, N countDowns. A spent latch never closes again.
Round-based work: simulation steps, staged batches, anything where all parties must finish round N before any starts round N + 1.
acquire takes a token, release returns one. No owner, no reentrancy, and a release without an acquire is legal.
Capping parallel calls, limiting a resource pool, adding backpressure: anything measured in permits rather than in parties.
arriveAndAwaitAdvance per phase; register and arriveAndDeregister move the party list between phases.
Multi-stage runs where workers join late or leave early: the party count is data, not a constant.
Both block until the other arrives, then each leaves with what the other brought. A third caller waits forever.
Pipeline handoff and double buffering: the pairing is structural, and both sides give and take in one step.
reading the board
- Solid squares are counts in motion; the accent pill is the moment the wait ends.
- Dashed shapes are parties still outside the tool: not yet acquired, not yet joined.
- Tags answer one question: can the same object be used again?
Each tool answers one shape of waiting: an event, a meeting, a capacity, a phase, a pair. Naming the shape first is most of the choice.
CountDownLatch: a gate that opens once
A latch is created with a count. Threads call await() and block until the count reaches zero, and other threads call countDown() to decrement it. When the count reaches zero, every waiter is released, and every later await() returns immediately.
That one-way nature is the defining trait, not a limitation to work around. There is no reset method and the count never rises again, so a latch is finished the moment it opens. It also means countDown() past zero is a harmless no-op: you cannot over-release it by mistake.
Two uses cover almost every case: the start gate, where N workers block on a latch of one and a single countDown releases them together, and the done gate, where a latch of N counts each finished worker down and one waiter waits for all of them without holding a reference to a single Thread.
CountDownLatch startGate = new CountDownLatch(1); // one release for every waiter CountDownLatch doneGate = new CountDownLatch(workers); for (int i = 0; i < workers; i++) { new Thread(() -> { try { startGate.await(); // all workers leave this line together work(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { doneGate.countDown(); // count down even on failure, or the gate never opens } }).start(); } startGate.countDown(); // main is ready: every waiter runs, and the latch cannot close again doneGate.await(); // wait for N workers without tracking N threads
A latch is a gate that opens once and never closes. If a second round has to wait as well, the tool you want is a barrier, not a latch with a bigger number.
CyclicBarrier: a rendezvous that resets itself
A barrier is created with a party count. Every party calls await() when it reaches the meeting line, and the call blocks until the last party arrives. Then all of them proceed together, and the barrier resets itself to the full party count for the next round.
The optional barrier action runs once per round, in the thread that arrives last, before anyone is released. That is where the shared state of a round belongs: fold the partial results, check the invariant, decide whether another round is needed.
Broken is a state, not just an exception. If one party is interrupted or times out while waiting, that caller throws, and every other party gets BrokenBarrierException: the barrier cannot know whether the missing party will ever arrive, so it refuses to release a possibly incomplete round. reset() clears a broken barrier, but it also throws BrokenBarrierException at every thread still waiting. Treat a broken barrier as a round that did not happen, and rebuild whatever state that round protected.
CyclicBarrier barrier = new CyclicBarrier(3, () -> { mergePartialResults(); // runs in the last party, once per generation }); Runnable worker = () -> { try { for (int round = 0; round < 5; round++) { computeOwnSlice(round); barrier.await(); // wait for the other two, then round N + 1 starts together } } catch (InterruptedException e) { Thread.currentThread().interrupt(); // keep the flag: cancellation travels up } catch (BrokenBarrierException e) { throw new IllegalStateException("round aborted", e); // the round did not happen } };
A broken barrier breaks for everyone. One interrupted or timed-out party throws BrokenBarrierException at all the others, because releasing half a round is worse than failing it.
Semaphore: a budget of permits
A semaphore holds a count of permits. acquire() takes one and blocks while none are free; release() puts one back. Nothing else is recorded: no owner, no thread identity, no reentrancy count.
That is exactly why a semaphore is not a lock. A lock must be released by the thread that acquired it; a semaphore may be released by any thread, and releasing without acquiring simply raises the permit count. The tool counts resources, and it does not enforce ownership.
The workhorse use is a cap on concurrency: acquire before starting an operation, release when it finishes, and no more than N operations are ever in flight. Because acquire() blocks the caller, it is also backpressure at the finest grain available: when the pool is saturated, the load generator feels it instead of the heap.
Two details matter in practice. fair = true makes acquire() queue waiters in arrival order instead of letting latecomers barge, which costs throughput and buys bounded waiting. And because permits are not tied to threads, each acquire/release pair must sit in one lexical scope: acquire, then try, then release in finally.
Semaphore slots = new Semaphore(8, true); // at most 8 calls in flight, waiters served in order slots.acquire(); // blocks when saturated: this is the backpressure try { callRemoteService(); } finally { slots.release(); // exactly one release per successful acquire }
A semaphore is not a lock: it is a budget of permits. It caps how much of a resource is in use at once, and it has no idea which thread is spending it.
synchronizer lab · three shapes of waiting
scenario
latch count
1 · closed
await() parked
await() parked
await() parked
Three workers start and park in startGate.await(). The latch holds a single count: one event is being waited for, by all three waiters.
outcome · start gate
a gate that opens once: N countDowns release every waiter, and nothing resets it
Start gate when one event releases many waiters; done gate when one waiter waits for many events. The latch is spent the moment it opens, so a second rendezvous needs a barrier.
Phaser: a barrier with a changing guest list
A phaser coordinates parties across many phases, and unlike a barrier it accepts that the set of parties changes. register() adds a party, arriveAndDeregister() removes one, and every party that stays calls arriveAndAwaitAdvance() to finish the current phase and wait for the others.
Phase numbers come from the phaser itself, so the round counter a barrier forces you to keep in a variable disappears. Registration takes effect from the next phase: a party that joins during phase 3 is counted in phase 4, not in the phase it arrived during.
The subclass hook onAdvance(phase, registeredParties) decides termination: return true and the phaser ends, releasing every waiter. That is how a run stops when a worker discovers there is no work left, without any thread having to count who remains.
Phaser phaser = new Phaser(1); // the coordinator is a registered party too for (Job job : jobs) { phaser.register(); // counted from the next phase onward pool.submit(() -> { workOnePhase(job); phaser.arriveAndDeregister(); // leaves when its own work is finished }); } for (int phase = 0; phase < phases; phase++) { workOnePhase(coordinatorJob); phaser.arriveAndAwaitAdvance(); // wait for every remaining party } phaser.arriveAndDeregister(); // last party out ends the run
A phaser is a barrier whose party list is data, not a constant. Reach for it when workers join and leave between rounds, a shape neither a barrier nor a latch can express.
Exchanger: the two-party swap
An exchanger has room for exactly two threads. Each calls exchange(value); both block until the other arrives, and then each receives what the other brought. One call, one swap, no counters and no party list.
That makes it the natural fit for the handoff between two stages of a pipeline: a filler produces into a buffer while a drainer empties the previous one, and a single exchange swaps the full buffer for the drained one. The pairing is structural, which is the whole point: an exchanger refuses to be more than a pair.
If a third thread calls exchange, it waits for a partner that will never come. That is not a defect to work around; it is the tool telling you that a queue, not an exchanger, is what the code needs.
Exchanger<byte[]> exchanger = new Exchanger<>(); // filler thread: fill a buffer, then swap it for a drained one byte[] target = exchanger.exchange(fullBuffer); // blocks until the drainer arrives // drainer thread: take the full buffer, hand back the drained one byte[] data = exchanger.exchange(drainedBuffer);
An exchanger has no third seat. The swap is a pairing decision; if the number of participants can vary, a queue is the honest tool.
Choosing, and the traps that survive the choice
The choice is a short sequence of questions, and the first answer that fits ends it.
- Do the waiters wait for events (counts going down), or for each other (everyone must arrive)? Events point to a latch, each other points to a barrier.
- Does the tool have to run a second time? No: latch. Yes with the same parties: barrier. Yes with parties that change: phaser.
- Is the thing being limited a pool of capacity rather than a moment in time? Then a semaphore, and thread identity is irrelevant to it.
- Is the pairing exactly two threads and the payload a swap? An exchanger.
- Still unsure? Default to an executor plus a done-gate latch: wait for submitted work instead of coordinating raw threads by hand.
- Reusing a latch by accident. await() on an open latch returns immediately, so round 2 silently loses its rendezvous. This is the classic why-did-round-2-start-early bug.
- A broken barrier needs reset(), and reset() breaks the waiters. Recovery is a rebuild, not a repair: discard the round and re-run it.
- release() in a finally that can run without acquire(). A failed or skipped acquire still adds a permit, and the cap inflates for good. Keep acquire outside the try, and release only after it succeeded.
- A semaphore used as a lock. No owner and no reentrancy: a thread that acquires twice can starve itself when the count runs out, with no owner identity for the runtime to detect.
- Timed waits that never check a deadline. await(timeout) returning is not evidence that the condition changed. Compute the deadline once and re-check the clock in the loop, as the wait-notify lesson shows for the monitor case.
Choose by the shape of the waiting, then let the tool's sharp edge shape the code. One-shot, reusable, counted, phased, paired: five questions, five answers.
Releasing a permit you never acquired is legal, and that is the trap
A semaphore has no owner, so nothing stops a finally block from adding a permit that was never taken: an interrupted acquire(), an early return before acquire(), and the cap now sits above the limit written in the code. Java will not throw, because release() from any thread is allowed by design (it is what makes handoff-style usage possible). Keep acquire() outside the try, call release() only after a successful acquire, and assert the permit count in tests.
Interview angles
CountDownLatch or CyclicBarrier?+
A latch is a one-shot gate: waiters wait for a count to hit zero, and the latch is then spent. A barrier is a reusable rendezvous: N parties wait for each other, then all continue, and it resets for the next round.
The other difference is who waits. With a latch, the waiters and the counters are usually different threads (main waits for workers). With a barrier, every thread is both a counter and a waiter.
Follow-up: What happens if one party never arrives at the barrier?
Can a CountDownLatch be reset or reused?+
No. It is one-shot by design: once the count reaches zero it never changes, and further await() calls return immediately. Reuse means constructing a new latch, or choosing a barrier or a phaser in the first place.
countDown() stops at zero and there is no count-up or reset method. Teams that need repeated rounds tend to discover this when round two starts with no rendezvous at all.
Common misconception: You can reset a latch by counting it back up or constructing it with a large count.
How is a Semaphore different from a ReentrantLock?+
A lock has an owner and a reentrancy count; a semaphore has only permits. Any thread may release a semaphore, it cannot be re-acquired reentrantly, and it models a pool of capacity rather than exclusive access.
That ownership difference is also why a semaphore does not document the same memory-visibility edges a lock does: acquiring and releasing only move a counter. Where a happens-before relationship is needed, a lock or a concurrent structure built on one remains the tool.
What happens to the other parties when a CyclicBarrier breaks?+
They receive BrokenBarrierException instead of being released. The barrier is unusable until reset(), and reset() itself throws BrokenBarrierException at any thread still waiting.
A party can be interrupted, can time out in await(timeout), or the barrier action itself can throw. The usual reaction is to abandon the round, rebuild the state it protected, and start again.
When would you move from CyclicBarrier to Phaser?+
When the set of parties changes between rounds. A phaser lets threads register and deregister, hands out phase numbers itself, and can terminate from onAdvance once the work is exhausted.
Registration counts from the next phase, so a joiner does not block the round already running, and arriveAndDeregister() lets a finished worker leave without stranding the others. That flexibility is why phasers show up in multi-stage pipelines and inside recursive task frameworks.
Why does Exchanger exist when a BlockingQueue can hand items over?+
An exchanger is a pair rendezvous with a swap: it guarantees exactly one partner, and both sides give and take in one atomic step. A queue decouples a producer from any particular consumer and adds capacity; an exchanger couples two known threads and adds none.
That makes it the natural fit for double buffering and two-stage pipelines, where the pairing is structural and the value flowing back matters as much as the value flowing forward.