How are CountDownLatch and CyclicBarrier built, and how does that explain why one is one-shot, the other reusable, and only the barrier can break?
answer
- count in AQS versus count behind a lock
- nothing raises the latch's state again
- last arrival installs a new Generation
- broken flag lives on the Generation
- a latch waiter adds nothing to the count
basics
~20 sCountDownLatch's count is AQS state that only decreases, so it is one-shot. CyclicBarrier's count sits behind a ReentrantLock and Condition and resets with each new Generation; one party leaving breaks the round, because the others need its arrival.
solid answer
~50 s`CountDownLatch` holds a private `Sync` subclass of `AbstractQueuedSynchronizer` whose `state` is the count. The constructor sets it, `countDown()` lowers it by CAS, and `await()` is a shared acquire that passes only at zero; nothing raises it again, so the latch is one-shot. `CyclicBarrier` has a `ReentrantLock`, a `Condition` called `trip`, a plain `int count` and a private `Generation` object. Each `await()` decrements `count` under the lock, and the last arrival runs the barrier action, signals everyone, restores `count` and installs a new `Generation`, which is why it is reusable. A woken waiter checks the `Generation` it joined to learn whether its round tripped or broke. Only a barrier breaks because its waiters are also what it counts: a party leaving by interrupt or timeout takes away an arrival the others need, while a latch waiter leaving changes no count.
code
java · 33 linesimport java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class GiveUp {
public static void main(String[] args) throws Exception {
// A waiter that times out on a latch leaves the latch as it found it.
CountDownLatch latch = new CountDownLatch(1);
System.out.println(latch.await(50, TimeUnit.MILLISECONDS)); // false
System.out.println(latch.getCount()); // 1
latch.countDown();
latch.countDown(); // no effect at zero
System.out.println(latch.getCount()); // 0
System.out.println(latch.await(50, TimeUnit.MILLISECONDS)); // true, and true from now on
// A party that times out on a barrier breaks it, and it stays broken until reset().
CyclicBarrier barrier = new CyclicBarrier(2);
try {
barrier.await(50, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println(barrier.isBroken()); // true
}
try {
barrier.await();
} catch (BrokenBarrierException e) {
System.out.println("still broken"); // no waiting: thrown at once
}
barrier.reset();
System.out.println(barrier.isBroken()); // false
}
}go deeper
Recall the two shapes: a latch is a counter that falls to zero once and stays there, and a barrier is a group of threads that wait for each other and then start over.
Explain the mechanics: shared AQS state with a CAS decrement on one side; a lock, a Condition, a plain count and a Generation object on the other. Walk through what the last arrival does and what a woken waiter checks.
Use the internals to predict failures: a waiter that times out or is interrupted breaks a barrier for every party but leaves a latch alone, while a worker that dies before arriving hangs untimed waiters on either. Use timed waits where a worker can die.
Weigh what each failure model costs a team: with timed waits, all-or-none breakage turns one slow party into a failed round for all, while a latch lets each waiter give up alone. Neither notices a worker that never arrives, so decide how the system detects that and recovers.
## Two ways to wait for a number to reach zero Both classes make threads wait until a count reaches zero. They differ in where the count lives, who lowers it, and what a waiting thread means to it. The private names below are JDK 27's implementation and are the same in JDK 25; only the public behaviour is a contract. | | `CountDownLatch` | `CyclicBarrier` | |---|---|---| | Built on | Private nested `Sync extends AbstractQueuedSynchronizer` | `ReentrantLock`, `Condition`, private nested `Generation` | | The count | AQS `state`, a `volatile int` changed by compare-and-set (CAS) | `count`, a plain `int` guarded by the lock | | Who lowers it | Any thread calling `countDown()`, which does not wait | Each party, by calling `await()` and waiting there | | At zero | Waiters are released and the count stays 0 | The count returns to `parties` and a new `Generation` starts | | A waiter gives up | Its own `await()` ends and the other waiters carry on | The round breaks for every waiting party | ## `CountDownLatch`: a count that can only fall **AbstractQueuedSynchronizer (AQS)** is the JDK's base class for building synchronizers: an `int` called `state` plus a queue of waiting threads. How that queue parks and wakes threads is covered with AQS and `LockSupport`. `CountDownLatch` holds a private subclass, `Sync`, and uses `state` as the count: - **Construction:** the constructor rejects a negative count, then `Sync` calls `setState(count)`, the only write that is not a decrement. - **`await()`** calls `acquireSharedInterruptibly(1)`. `tryAcquireShared` returns `(getState() == 0) ? 1 : -1`, so a thread passes only at zero and otherwise queues and parks. - **`countDown()`** calls `releaseShared(1)`. `tryReleaseShared` loops on `compareAndSetState(c, nextc)` with `nextc` one below `c`. It returns `true` only on the transition to zero, and `false` if `state` is already 0, so an extra `countDown()` does nothing. **Shared mode** is why every waiter gets through. When the count reaches zero, AQS wakes the first queued thread, which succeeds, becomes the queue's head and wakes the next shared waiter, so the release runs down the queue. This makes the latch **one-shot by construction**: `Sync` is private, it has no method that raises `state`, and the public class has no reset. ## `CyclicBarrier`: a count inside a round `CyclicBarrier` has no AQS subclass of its own; the `ReentrantLock` it holds uses AQS inside. Its private fields are `lock`, `trip` (a `Condition` from that lock), `parties`, `barrierCommand`, `count` and `generation`. Each `await()` reaches the private `dowait` method, which runs these steps in order while holding the lock: 1. If the current `Generation` is already broken, throw `BrokenBarrierException`. If the thread's interrupted flag is set, break the barrier and throw `InterruptedException`. 2. Decrement `count`. The new value is the arrival index that `await()` returns, so the last arrival gets 0. 3. If that value is 0, run the barrier action on this thread and call `nextGeneration()`, which does `trip.signalAll()`, `count = parties` and `generation = new Generation()`. 4. Otherwise wait on `trip`, which releases the lock during the wait, and after each wakeup make the three checks below. **Reusable** follows from step 3: the count is ordinary state, and the last arrival puts it back. ## Why a `Generation` object and not a flag `Generation` is a private class with one field, `boolean broken`. Its job is **identity**. Each waiter keeps a local reference to the `Generation` it joined, because by the time it reacquires the lock, a later round may have begun and the barrier's current fields may describe someone else's round. So after a wakeup it asks: - `g.broken` is true: my round failed, so throw `BrokenBarrierException`. - `g != generation`: my round finished normally, so return my index. - Timed and out of time: break the barrier and throw `TimeoutException`. Otherwise keep waiting. `reset()` shows why the object matters. It calls `breakBarrier()` and then `nextGeneration()`, so threads waiting in the old round see the old object's flag and throw, while new arrivals join the fresh one. ## Why only the barrier can break The Javadoc names an **all-or-none breakage model**. The private `breakBarrier()` sets `generation.broken = true`, restores `count` and signals every waiter. It runs when: - a party is interrupted on entry, or while its round is still open; - a timed `await` runs out of time; - the barrier action throws; - `reset()` is called. The model fits what a party is. On a barrier, **waiting is the contribution**: the others are waiting for this thread's arrival, so a party that leaves takes away something the round needs. A latch separates those roles. Its waiters add nothing to the count and its `countDown()` callers do not wait. A waiter that times out gets `false`, one that is interrupted gets `InterruptedException`, and `state` is not touched: AQS only cancels that thread's queue node. `Sync` has nowhere to record a failure. A worker that dies before `countDown()` leaves the count above zero, and an untimed `await()` keeps waiting with no exception. A barrier party that dies before calling `await()` is no different: it never reaches `dowait`, breaks nothing, and leaves the others waiting. A broken barrier **stays broken**. `breakBarrier()` restores `count` but installs no new `Generation`, so every later `await()` throws `BrokenBarrierException` at once until `reset()`. The Javadoc warns that a reset after a breakage can be complicated and that a new barrier may be preferable. ## What you can observe from this - `CountDownLatch.getCount()` reads `state` without taking a lock, while `CyclicBarrier.isBroken()` and `getNumberWaiting()` take the barrier's lock. - The barrier action runs while the last arrival holds that lock, so a slow action delays every party and those two methods as well.
- Why does a woken CyclicBarrier waiter check its Generation reference instead of checking whether count went back to parties?`count` is restored on a trip and on a break alike, and by the time a waiter reacquires the lock, new arrivals may have lowered it again. So its value says nothing about one round. The reference does: `broken` set means that round failed, a different current object means it tripped, and neither means keep waiting.
- What does a CyclicBarrier do when an interrupt reaches a waiting party just after the last party has arrived?The round stands. In `dowait`, an interrupted waiter breaks the barrier only if `g == generation && ! g.broken`, meaning its round is still open. Otherwise it restores its interrupted flag and carries on, and the source treats that interrupt as belonging to whatever the thread does next. Since its round tripped, `await()` returns its index normally.
- You need a countdown that can be re-armed for each batch. Can you subclass CountDownLatch to add a reset?Not in any useful way. The class is not final, but `Sync` and the `sync` field are private, so a subclass cannot reach `state`. Create a new `CountDownLatch` per batch, which means waiters must be given the new instance, or use `CyclicBarrier` if the threads doing the work can wait for each other.
- CyclicBarrier is built on its own AQS subclass, just as CountDownLatch is, so they share one design.
- Calling countDown() on a latch already at zero throws an exception.
- One waiter timing out on a CountDownLatch breaks the latch for the other waiters.
- After a barrier breaks, the next await() starts a fresh round because count was restored.
- The Generation object stores the remaining count for its round.
- CyclicBarrier's count is an atomic variable changed by CAS, like the latch's state.
- CountDownLatch
- Java 1.5
- CyclicBarrier
- Java 1.5
- AbstractQueuedSynchronizer
- Java 1.5
- ReentrantLock
- Java 1.5
- Condition
- Java 1.5
Assumes JDK 27; the private members named here are implementation, not contract, and are the same in JDK 25.
context
- AbstractQueuedSynchronizer (Java SE 27 & JDK 27)docs.oracle.com
- CyclicBarrier.java at jdk-27-gagithub.com
- CountDownLatch.java at jdk-27-gagithub.com