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.

Share

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 has two classes for this, both added in Java 5, and they solve different problems.

  • A CountDownLatch holds a count fixed at creation. Any thread can call countDown() to decrease it, and threads that call await() block until it reaches zero. It is built on AbstractQueuedSynchronizer, 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.
  • A CyclicBarrier is created for a number of parties. Each party calls await() and blocks until all of them have arrived; then all are released together and the barrier resets for the next round. Internally it is a ReentrantLock with one Condition 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.

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.

Tools for making threads wait for each other
ToolSinceReusableWho waitsBest for
Thread.joinJava 1.0Not applicableOne thread waits for another to endThreads you created yourself
CountDownLatchJava 5NoAny number of threads wait for N eventsWaiting for N tasks; start gates
CyclicBarrierJava 5Yes, automaticallyN threads wait for each otherIterative work in fixed rounds
PhaserJava 7YesA changing number of partiesRounds where parties join and leave
ExecutorService.invokeAllJava 5Not applicableThe caller waits for a list of tasksFan-out work that returns results
CompletableFuture.allOfJava 8Not applicableNobody blocks; a callback runsAsynchronous fan-out

Both classes also give memory visibility. Actions in a thread before countDown() happen-before actions after the matching await() returns, so results written by the workers can be read safely by the waiter. For a barrier, actions before await() happen-before the barrier action, which happens-before everything after the other parties return. Each program was run on JDK 21.

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.

Java
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:

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}
  • await(500, MILLISECONDS) 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.
  • The "reviews" service threw, but the count still went down, because countDown() sits in finally. The failure was recorded as a result, so the caller can tell a failed service from a missing one.
  • The worker threads are daemon threads, so the stuck call does not keep the JVM alive after main ends. In a server you would run them on an executor and cancel the late task.
  • The results map is a ConcurrentHashMap because several workers write to it at once. Reading it after await is safe for the entries written before each countDown; the slow worker could still add its entry later, so do not assume the map is frozen after a timeout.

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() opens it for all of them. This is how load tests and concurrency tests make threads collide on purpose. The program creates four runners 50 ms apart, then releases them together, and checks the start times instead of printing them, since the exact order changes every run.

Java
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:

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 ready latch runs the other way: each runner counts it down, and main waits on it, so the gate opens only when everyone is in position. The finished latch then waits for them all. Three latches with three different counts and roles are a common pattern.
  • 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.

Java
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:

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
  1. The "bad" task threw before reaching countDown(), so the count stayed at 1. A timed await returned false; a plain await() would have blocked forever with no error anywhere except the thread's stack trace. Always call countDown() in a finally block, and prefer timed waits in production code.
  2. 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 await returns at once. A latch cannot be reset; if you need another round, create a new latch or use a CyclicBarrier or Phaser.
  3. 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 IllegalArgumentException. The count also cannot grow; when the number of tasks is not known in advance, use a Phaser.

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.

Java
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:

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.
  • await() returns an arrival index: getParties() - 1 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.
  • 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.

Java
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:

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 TimeoutException and broke the barrier. That released the patient party with BrokenBarrierException, even though it had no timeout of its own. Without the impatient one, the patient thread would have waited forever.
  • Once broken, the barrier stays broken: a late arrival fails immediately. reset() repairs it, but if any party is still waiting it receives BrokenBarrierException, so reset only when all parties agree to restart. Often it is cleaner to create a new barrier.
  • Handle both exceptions in every party. A party that catches BrokenBarrierException should stop its round, because the others have already stopped theirs.

Simpler alternatives for fan-out work

Many uses of CountDownLatch are really "run these tasks and collect their results". Executors and CompletableFuture do that with results and errors built in. The program runs the same three service calls both ways and then shows how a failure reaches the caller.

Java
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:

Output
invokeAll total:           180
CompletableFuture total:   180
failure seen by caller:    HTTP 500 from reviews
  • invokeAll 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 own Future.
  • CompletableFuture.allOf returns a future that completes when all inputs complete, so no thread has to sit in await. The thenApply sums the results once they are all there.
  • A failure is not lost: Future.get rethrows it wrapped in ExecutionException. With a latch you must capture failures yourself, as the first example did.
  • ExecutorService is AutoCloseable since Java 19, and close() waits for submitted tasks to finish, which is why it can sit in try-with-resources.

See ExecutorService and CompletableFuture for these in depth. A latch is still the better fit when the waiting threads are not the ones that started the work, or for a start gate.

Choosing between them

Which coordination tool to use
SituationUse
Wait until N one-off events have happenedCountDownLatch(N), with countDown() in finally and a timed await
Release many threads at the same momentCountDownLatch(1) as a gate
N threads repeat steps that depend on each otherCyclicBarrier(N, action)
The number of participants changesPhaser
Run tasks and collect results or errorsinvokeAll or CompletableFuture.allOf
Limit how many threads do something at onceSemaphore
Two threads swap data at a meeting pointExchanger

For the threads themselves, see thread basics.