CountDownLatch and CyclicBarrier
Both classes make threads wait for each other, but for different shapes of problem. A CountDownLatch lets threads wait until a count of events reaches zero, once. A CyclicBarrier makes a fixed group of threads meet at a point, round after round. This page explains how each one works, runs the common patterns with deadlines and failures, shows the traps, and compares them with executors and CompletableFuture.
Contents
Latches and barriers: what they coordinate
Threads often need to wait for each other without passing data: a request handler waits until three backend calls have finished, or a simulation's worker threads must all finish step 5 before any of them starts step 6. java.util.concurrent
- A
holds a count fixed at creation. Any thread can callCountDownLatch to decrease it, and threads that callcountDown() block until it reaches zero. It is built onawait() , the framework under most of the package's locks, with the count stored as the synchronizer's state. Once the count reaches zero the latch stays open forever: it is a one-shot gate.AbstractQueuedSynchronizer - A
is created for a number of parties. Each party callsCyclicBarrier and blocks until all of them have arrived; then all are released together and the barrier resets for the next round. Internally it is aawait() with oneReentrantLock and a "generation" object that changes each round. An optional barrier action runs once per round, in the last thread to arrive, before the others are released.Condition
The key difference: with a latch, the threads that count down are usually not the ones that wait, and nobody waits for the counters. With a barrier, the same threads both arrive and wait, and they meet again and again.
| Tool | Since | Reusable | Who waits | Best for |
|---|---|---|---|---|
Thread.join | Java 1.0 | Not applicable | One thread waits for another to end | Threads you created yourself |
CountDownLatch | Java 5 | No | Any number of threads wait for N events | Waiting for N tasks; start gates |
CyclicBarrier | Java 5 | Yes, automatically | N threads wait for each other | Iterative work in fixed rounds |
| Java 7 | Yes | A changing number of parties | Rounds where parties join and leave | |
ExecutorService.invokeAll | Java 5 | Not applicable | The caller waits for a list of tasks | Fan-out work that returns results |
CompletableFuture.allOf | Java 8 | Not applicable | Nobody blocks; a callback runs | Asynchronous fan-out |
Both classes also give memory visibility. Actions in a thread before countDown()await()await()
Waiting for N tasks with a deadline
A page needs data from four services and has a 500 ms budget. Each service's delay is fixed so that the outcome is the same every run: two succeed, one throws an exception, and one takes 3 seconds, far longer than the budget.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class LatchDemo {
// Pretend remote services: name and how long each call takes
record Service(String name, long millis, boolean fails) { }
public static void main(String[] args) throws InterruptedException {
List<Service> services = List.of(
new Service("prices", 100, false),
new Service("stock", 150, false),
new Service("reviews", 50, true), // throws an exception
new Service("recommendations", 3000, false)); // far too slow
Map<String, String> results = new ConcurrentHashMap<>();
CountDownLatch done = new CountDownLatch(services.size());
long t0 = System.nanoTime();
for (Service s : services) {
Thread.ofPlatform().daemon().start(() -> {
try {
Thread.sleep(s.millis());
if (s.fails()) {
throw new IllegalStateException("HTTP 500");
}
results.put(s.name(), "ok after " + s.millis() + " ms");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (RuntimeException e) {
results.put(s.name(), "failed: " + e.getMessage());
} finally {
done.countDown(); // always, even on failure
}
});
}
boolean allArrived = done.await(500, TimeUnit.MILLISECONDS); // a page budget
long waited = (System.nanoTime() - t0) / 100000000 * 100;
System.out.println("all arrived: " + allArrived + ", count still " + done.getCount()
+ ", waited about " + waited + " ms");
System.out.println("results: " + new TreeMap<>(results));
}
}
Output:
all arrived: false, count still 1, waited about 500 ms
results: {prices=ok after 100 ms, reviews=failed: HTTP 500, stock=ok after 150 ms}
returned false after about 500 ms, with the count still 1: the slow service had not finished. The caller renders the page with what it has. Without the timeout, the request would have waited the full 3 seconds.await(500, MILLISECONDS)- The "reviews" service threw, but the count still went down, because
sits incountDown() . The failure was recorded as a result, so the caller can tell a failed service from a missing one.finally - The worker threads are daemon threads, so the stuck call does not keep the JVM alive after
ends. In a server you would run them on an executor and cancel the late task.main - The results map is a
because several workers write to it at once. Reading it afterConcurrentHashMap is safe for the entries written before eachawait ; the slow worker could still add its entry later, so do not assume the map is frozen after a timeout.countDown
A start gate: releasing threads at the same moment
A latch with count 1 is a gate: every thread waits on it, and one countDown()
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
public class StartGate {
public static void main(String[] args) throws InterruptedException {
int runners = 4;
CountDownLatch ready = new CountDownLatch(runners); // runners -> main
CountDownLatch go = new CountDownLatch(1); // main -> all runners
CountDownLatch finished = new CountDownLatch(runners);
ConcurrentLinkedQueue<Long> startTimes = new ConcurrentLinkedQueue<>();
long created = System.nanoTime();
for (int i = 1; i <= runners; i++) {
Thread.sleep(50); // threads are created slowly
new Thread(() -> {
ready.countDown();
try {
go.await(); // everyone waits at the gate
startTimes.add(System.nanoTime());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
finished.countDown();
}
}, "runner-" + i).start();
}
ready.await();
long opened = System.nanoTime();
System.out.println("runners created over about "
+ (opened - created) / 100000000 * 100 + " ms");
go.countDown(); // releases all of them at once
finished.await();
List<Long> times = new ArrayList<>(startTimes);
long first = times.stream().mapToLong(Long::longValue).min().orElseThrow();
long last = times.stream().mapToLong(Long::longValue).max().orElseThrow();
System.out.println("runners started: " + times.size());
System.out.println("all started within 10 ms of each other: "
+ ((last - first) < 10000000));
System.out.println("none started before the gate opened: " + (first >= opened));
}
}
Output:
runners created over about 200 ms
runners started: 4
all started within 10 ms of each other: true
none started before the gate opened: true
- The runners were created over about 200 ms, yet all four started within 10 ms of each other, and none before the gate opened. Without the gate, the first runner would have had a 150 ms head start, and a test meant to find a race would rarely find it.
- The
latch runs the other way: each runner counts it down, andready waits on it, so the gate opens only when everyone is in position. Themain latch then waits for them all. Three latches with three different counts and roles are a common pattern.finished - The order in which the runners actually start after the gate opens is up to the scheduler, and it varies from run to run.
Latch traps
A latch has almost no API, and its traps come from that simplicity. The program shows a task that dies before it counts down, a latch counted down too often, and the edge cases of the count.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class LatchTraps {
public static void main(String[] args) throws InterruptedException {
// Trap 1: countDown() skipped when the task throws
CountDownLatch latch = new CountDownLatch(2);
Thread.setDefaultUncaughtExceptionHandler((t, e) ->
System.out.println("1. " + t.getName() + " died: " + e.getMessage()));
Thread good = new Thread(latch::countDown, "good");
Thread bad = new Thread(() -> {
if (latch.getCount() >= 0) {
throw new IllegalArgumentException("parse error");
}
latch.countDown(); // never reached
}, "bad");
good.start();
bad.start();
good.join();
bad.join();
System.out.println("1. await(300 ms) returned " + latch.await(300, TimeUnit.MILLISECONDS)
+ ", count " + latch.getCount() + " (await() would wait forever)");
// Trap 2: a latch is one-shot; extra countDown calls are ignored
CountDownLatch once = new CountDownLatch(1);
once.countDown();
once.countDown();
once.countDown();
System.out.println("2. after 3 countDowns on count 1: getCount = " + once.getCount());
long t0 = System.nanoTime();
once.await();
once.await();
System.out.println("2. two more awaits took " + (System.nanoTime() - t0) / 1000000
+ " ms: an open latch stays open");
// Trap 3: the count is fixed at creation; new CountDownLatch(0) is open at once
CountDownLatch zero = new CountDownLatch(0);
System.out.println("3. latch(0) await returns at once: " + zero.await(0, TimeUnit.SECONDS));
try {
new CountDownLatch(-1);
} catch (IllegalArgumentException e) {
System.out.println("3. latch(-1): IllegalArgumentException: " + e.getMessage());
}
}
}
Output:
1. bad died: parse error
1. await(300 ms) returned false, count 1 (await() would wait forever)
2. after 3 countDowns on count 1: getCount = 0
2. two more awaits took 0 ms: an open latch stays open
3. latch(0) await returns at once: true
3. latch(-1): IllegalArgumentException: count < 0
- The "bad" task threw before reaching
, so the count stayed at 1. A timedcountDown() returned false; a plainawait would have blocked forever with no error anywhere except the thread's stack trace. Always callawait() in acountDown() block, and prefer timed waits in production code.finally - Counting down past zero is silently ignored: three calls on a count of 1 leave it at 0. An open latch stays open, and every later
returns at once. A latch cannot be reset; if you need another round, create a new latch or use aawait orCyclicBarrier .Phaser - A latch created with count 0 is open from the start, which is useful when the number of tasks can be zero. A negative count throws
. The count also cannot grow; when the number of tasks is not known in advance, use aIllegalArgumentExceptionPhaser .
CyclicBarrier: work in rounds
A barrier fits iterative algorithms where each step needs the complete result of the previous one. Here three threads smooth a row of 9 numbers: in every step, each cell becomes the average of itself and its two neighbours. Each thread owns three cells, and the starting row is a single spike of 90, so the spread is easy to follow and the sum must stay 90.
import java.util.Arrays;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class BarrierDemo {
// Smooths a row of numbers: each step, every cell becomes the average of its neighbours.
// Three threads each own a third of the row; step N+1 needs all of step N.
public static void main(String[] args) throws InterruptedException {
int workers = 3;
double[][] grid = {{0, 0, 0, 90, 0, 0, 0, 0, 0}, new double[9]};
int[] step = {0};
// The barrier action runs once per round, in the last thread to arrive
CyclicBarrier barrier = new CyclicBarrier(workers, () -> {
step[0]++;
double[] now = grid[step[0] % 2];
StringBuilder row = new StringBuilder();
for (double v : now) {
row.append(String.format("%5.1f", v));
}
System.out.printf("after step %d:%s sum %.1f%n", step[0], row,
Arrays.stream(now).sum());
});
Thread[] threads = new Thread[workers];
for (int w = 0; w < workers; w++) {
int from = w * 3;
threads[w] = new Thread(() -> {
try {
for (int s = 0; s < 4; s++) {
double[] src = grid[s % 2];
double[] dst = grid[(s + 1) % 2];
for (int i = from; i < from + 3; i++) {
double left = i > 0 ? src[i - 1] : src[i];
double right = i < src.length - 1 ? src[i + 1] : src[i];
dst[i] = (left + src[i] + right) / 3;
}
int arrival = barrier.await(); // wait for the other thirds
if (arrival == 0 && s == 3) {
System.out.println("last arrival index is 0; parties = "
+ barrier.getParties());
}
}
} catch (InterruptedException | BrokenBarrierException e) {
Thread.currentThread().interrupt();
}
});
threads[w].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("barrier reused for 4 rounds, broken = " + barrier.isBroken());
}
}
Output:
after step 1: 0.0 0.0 30.0 30.0 30.0 0.0 0.0 0.0 0.0 sum 90.0
after step 2: 0.0 10.0 20.0 30.0 20.0 10.0 0.0 0.0 0.0 sum 90.0
after step 3: 3.3 10.0 20.0 23.3 20.0 10.0 3.3 0.0 0.0 sum 90.0
after step 4: 5.6 11.1 17.8 21.1 17.8 11.1 4.4 1.1 0.0 sum 90.0
last arrival index is 0; parties = 3
barrier reused for 4 rounds, broken = false
- The spike spreads one cell further in each direction per step, and the sum stays exactly 90.0, which shows no thread read a half-finished row. Each thread reads its neighbours' cells from the previous step, so it must not start step 2 until all of step 1 is written. The barrier enforces exactly that.
- The program uses two arrays and alternates between them, so a step reads one and writes the other. With a single array, a fast thread could overwrite cells its neighbour still needs to read in the same step.
- The barrier action printed each row once per step. It runs in the last thread to arrive, while the others are still waiting, so it can safely read the whole row and is a natural place for a convergence check or a progress log.
returns an arrival index:await() for the first thread to arrive and 0 for the last. One thread per round sees 0, which gives you a way to pick one thread for extra work without the barrier action.getParties() - 1- The same barrier served all 4 rounds without being recreated, which is the "cyclic" in its name.
When a party never arrives: broken barriers
A barrier is all or nothing. If one party times out, is interrupted, or the barrier action throws, the barrier is broken, and every other waiting party is released with an exception. The barrier below expects 3 parties, but only 2 come: one waits with no timeout, the other gives up after 300 ms. The outcomes are collected and printed in a fixed order after both threads finish.
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class BrokenBarrier {
public static void main(String[] args) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(3); // expects 3, only 2 will come
Map<String, String> outcome = new ConcurrentHashMap<>();
Thread patient = new Thread(() -> {
try {
barrier.await(); // no timeout
outcome.put("patient", "passed");
} catch (BrokenBarrierException e) {
outcome.put("patient", "BrokenBarrierException: someone else gave up");
} catch (InterruptedException e) {
outcome.put("patient", "interrupted");
}
});
Thread impatient = new Thread(() -> {
try {
barrier.await(300, TimeUnit.MILLISECONDS);
outcome.put("impatient", "passed");
} catch (TimeoutException e) {
outcome.put("impatient", "TimeoutException: gave up, barrier broken");
} catch (BrokenBarrierException | InterruptedException e) {
outcome.put("impatient", e.toString());
}
});
patient.start();
impatient.start();
patient.join();
impatient.join();
new TreeMap<>(outcome).forEach((k, v) -> System.out.println(k + ": " + v));
System.out.println("isBroken: " + barrier.isBroken());
try {
barrier.await(); // a broken barrier fails at once
} catch (BrokenBarrierException e) {
System.out.println("late arrival: BrokenBarrierException immediately");
}
barrier.reset();
System.out.println("after reset, isBroken: " + barrier.isBroken()
+ ", waiting: " + barrier.getNumberWaiting());
}
}
Output:
impatient: TimeoutException: gave up, barrier broken
patient: BrokenBarrierException: someone else gave up
isBroken: true
late arrival: BrokenBarrierException immediately
after reset, isBroken: false, waiting: 0
- The impatient party got
and broke the barrier. That released the patient party withTimeoutException , even though it had no timeout of its own. Without the impatient one, the patient thread would have waited forever.BrokenBarrierException - Once broken, the barrier stays broken: a late arrival fails immediately.
repairs it, but if any party is still waiting it receivesreset() , so reset only when all parties agree to restart. Often it is cleaner to create a new barrier.BrokenBarrierException - Handle both exceptions in every party. A party that catches
should stop its round, because the others have already stopped theirs.BrokenBarrierException
Simpler alternatives for fan-out work
Many uses of CountDownLatchCompletableFuture
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
public class Alternatives {
static int call(String service) throws InterruptedException {
Thread.sleep(50L * service.length()); // pretend remote call
return service.length() * 10;
}
public static void main(String[] args) throws Exception {
List<String> services = List.of("prices", "stock", "reviews");
// invokeAll: submit all, wait for all, results in the same order as the tasks
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
List<Callable<Integer>> tasks = services.stream()
.<Callable<Integer>>map(s -> () -> call(s))
.toList();
int total = 0;
for (Future<Integer> f : pool.invokeAll(tasks)) {
total += f.get();
}
System.out.println("invokeAll total: " + total);
}
// CompletableFuture.allOf: the same fan-out without blocking a thread to wait
List<CompletableFuture<Integer>> futures = services.stream()
.map(s -> CompletableFuture.supplyAsync(() -> {
try {
return call(s);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}))
.toList();
int total = CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
.thenApply(v -> futures.stream().mapToInt(CompletableFuture::join).sum())
.get();
System.out.println("CompletableFuture total: " + total);
// A failure is reported, not hidden: get() rethrows it
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Integer> f = pool.submit(() -> {
throw new IllegalStateException("HTTP 500 from reviews");
});
f.get();
} catch (ExecutionException e) {
System.out.println("failure seen by caller: " + e.getCause().getMessage());
}
}
}
Output:
invokeAll total: 180
CompletableFuture total: 180
failure seen by caller: HTTP 500 from reviews
submits all tasks and waits until every one is done, returning the futures in task order. Here 60 + 50 + 70 = 180. There is no counter to forget and no shared map: each result comes back through its owninvokeAll .Future returns a future that completes when all inputs complete, so no thread has to sit inCompletableFuture.allOf . Theawait sums the results once they are all there.thenApply- A failure is not lost:
rethrows it wrapped inFuture.get . With a latch you must capture failures yourself, as the first example did.ExecutionException isExecutorService since Java 19, andAutoCloseable waits for submitted tasks to finish, which is why it can sit in try-with-resources.close()
See
Choosing between them
| Situation | Use |
|---|---|
| Wait until N one-off events have happened | CountDownLatch(N)countDown()finallyawait |
| Release many threads at the same moment | CountDownLatch(1) |
| N threads repeat steps that depend on each other | CyclicBarrier(N, action) |
| The number of participants changes | |
| Run tasks and collect results or errors | invokeAllCompletableFuture.allOf |
| Limit how many threads do something at once | |
| Two threads swap data at a meeting point |
For the threads themselves, see