Skip to lesson

CyclicBarrier: meet and continue together

A CyclicBarrier is a meeting point for a fixed group of threads. Each thread calls await() when it reaches the point and waits there; when the last one arrives, all of them continue together, and the barrier is ready for the next meeting.

Parties that wait for each other

A CyclicBarrier makes a fixed group of threads wait for each other at a meeting point, then releases them all together. It resets itself, so the same barrier can be used again for the next round.

new CyclicBarrier(n) creates a barrier for n threads, called parties. Each party calls await() and blocks. When the n-th party arrives, the barrier trips: every waiting party is released at once.

A CyclicBarrier for 3 parties. Threads A, B and C reach the barrier at different times. A and B wait. When C, the last party, arrives, the barrier trips and A, B and C all continue together. The barrier then resets for the next round.

Example 1 · Three friends meet at the fest gate

FestGateDemo.javaJava
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
public class FestGateDemo {    public static void main(String[] args) throws InterruptedException {        CyclicBarrier gate = new CyclicBarrier(3);        String[] friends = {"Asha", "Bala", "Chitra"};        long[] travelMs = {80, 20, 50};        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++) {            String name = friends[i];            long ms = travelMs[i];            threads[i] = new Thread(() -> {                try {                    Thread.sleep(ms);                   // travelling to college                    System.out.println(name + " reached the gate");                    gate.await();                       // wait for the others                    System.out.println(name + " goes in");                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } catch (BrokenBarrierException e) {                    System.out.println(name + ": the meeting was cancelled");                }            }, name);            threads[i].start();        }
        for (Thread t : threads) {            t.join();        }        System.out.println("All three are inside the fest");    }}
Sample output
Bala reached the gate
Chitra reached the gate
Asha reached the gate
Asha goes in
Bala goes in
Chitra goes in
All three are inside the fest

What this code does

  • Bala and Chitra arrive first and block in await(). Asha's arrival is the third, so the barrier trips and all three are released together.
  • The order inside each group changes from run to run. What never changes: all three "reached" lines come before any "goes in" line, because nobody passes await() until everyone has arrived.
  • await() throws InterruptedException and BrokenBarrierException, so the thread body catches both.

Think of three friends who agree to meet at the college gate before entering the fest. Whoever comes first waits. Nobody goes in until all three are there. Unlike a CountDownLatch, the threads that wait are the same threads that arrive; nobody counts down for them. await() also returns a number, the arrival index: getParties() - 1 for the first thread to arrive and 0 for the last one. Most code ignores it.

The barrier action

A barrier action is a Runnable you pass as the second constructor argument: new CyclicBarrier(n, action). It runs once each time the barrier trips, before any party is released.

Example 2 · Barrier action: add up the answer sheet

AnswerSheetBarrierDemo.javaJava
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
public class AnswerSheetBarrierDemo {    public static void main(String[] args) throws InterruptedException {        String[] parts = {"Section A", "Section B", "Section C"};        int[][] questionMarks = {{8, 9, 7}, {10, 6}, {12, 9, 11}};        int[] partTotal = new int[3];
        Runnable combine = () -> {                  // runs once, when all 3 arrive            int total = 0;            for (int i = 0; i < 3; i++) {                System.out.println(parts[i] + ": " + partTotal[i]);                total += partTotal[i];            }            System.out.println("Total: " + total + "/100, " + (total >= 40 ? "PASS" : "FAIL"));        };        CyclicBarrier allChecked = new CyclicBarrier(3, combine);
        Thread[] evaluators = new Thread[3];        for (int i = 0; i < 3; i++) {            int p = i;            evaluators[i] = new Thread(() -> {                for (int m : questionMarks[p]) {                    partTotal[p] += m;                }                try {                    allChecked.await();                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } catch (BrokenBarrierException e) {                    System.out.println("Evaluation cancelled");                }            }, "evaluator-" + (i + 1));            evaluators[i].start();        }
        for (Thread t : evaluators) {            t.join();        }    }}
Output
Section A: 24
Section B: 16
Section C: 32
Total: 72/100, PASS

What this code does

  • Three evaluators each total one section and then wait. When the third arrives, the barrier runs combine once, in that last thread, before releasing anyone.
  • combine reads partTotal without locks. That is safe: everything a thread did before await() is visible to the barrier action.
  • Only the barrier action prints, and it prints in a fixed order, so the output is the same on every run.

The action runs in the thread that arrived last; Java does not start a new thread for it. Because every other party is still waiting, the action can safely read what all of them wrote and combine it: add up partial totals, print a round summary, or prepare the next round. Keep the action short. While it runs, all parties are stuck at the barrier. If the action throws an exception, the barrier breaks (see the last section).

Reusing a barrier across rounds

The barrier is cyclic: after it trips, it resets itself to zero arrivals and can be used again. The same threads can meet at the same barrier round after round, with no new object.

Example 3 · One barrier, three days of sales

DailySalesDemo.javaJava
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
public class DailySalesDemo {    static int day = 0;
    public static void main(String[] args) throws InterruptedException {        int[][] sales = {              // rupees per day, one row per counter            {1200, 900, 1500},            {800, 1100, 700},            {950, 1000, 1300}        };        int[] today = new int[3];
        CyclicBarrier endOfDay = new CyclicBarrier(3, () -> {            day++;            int total = today[0] + today[1] + today[2];            System.out.println("Day " + day + " total: Rs " + total);        });
        Thread[] counters = new Thread[3];        for (int c = 0; c < 3; c++) {            int id = c;            counters[c] = new Thread(() -> {                try {                    for (int d = 0; d < 3; d++) {                        today[id] = sales[id][d];     // this counter's sales for day d                        endOfDay.await();             // wait for the other counters                    }                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } catch (BrokenBarrierException e) {                    System.out.println("Day closing cancelled");                }            }, "counter-" + (c + 1));            counters[c].start();        }
        for (Thread t : counters) {            t.join();        }        System.out.println("Rounds: " + day + ", parties: " + endOfDay.getParties()                + ", waiting now: " + endOfDay.getNumberWaiting());    }}
Output
Day 1 total: Rs 2950
Day 2 total: Rs 3000
Day 3 total: Rs 3500
Rounds: 3, parties: 3, waiting now: 0

What this code does

  • Each counter loops over three days and calls await() at the end of each day. The same barrier trips three times; after each trip it resets itself for the next day.
  • No counter can write day 2's sales until the barrier action has printed day 1, because every counter is still waiting while the action runs. So today is never overwritten too early.
  • At the end, getNumberWaiting() is 0: the barrier is clean and ready for another round. A CountDownLatch would have needed a new object for each day.

This fits work done in steps, where step 2 needs every result from step 1: a daily sales report from many counters, rounds of a quiz game, or a simulation that moves forward one tick at a time. Each party runs a loop: do this round's work, then await(). A CountDownLatch cannot do this, because once it reaches zero it stays open.

BrokenBarrierException

A barrier becomes broken when one party cannot finish the meeting. Every waiting party then gets a BrokenBarrierException instead of continuing.

Example 4 · A friend who never comes: timeout and a broken barrier

BrokenBarrierDemo.javaJava
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class BrokenBarrierDemo {    public static void main(String[] args) throws InterruptedException {        CyclicBarrier gate = new CyclicBarrier(3);        String[] result = new String[2];
        Thread asha = new Thread(() -> {            try {                gate.await(200, TimeUnit.MILLISECONDS);  // waits at most 200 ms                result[0] = "went in";            } catch (TimeoutException e) {                result[0] = "TimeoutException";            } catch (BrokenBarrierException e) {                result[0] = "BrokenBarrierException";            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, "Asha");
        Thread bala = new Thread(() -> {            try {                gate.await();                            // no timeout                result[1] = "went in";            } catch (BrokenBarrierException e) {                result[1] = "BrokenBarrierException";            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }, "Bala");
        asha.start();        bala.start();        asha.join();        bala.join();
        System.out.println("Asha: " + result[0]);        System.out.println("Bala: " + result[1]);        System.out.println("Broken: " + gate.isBroken());
        try {            gate.await();                                // a late arrival        } catch (BrokenBarrierException e) {            System.out.println("Late arrival: BrokenBarrierException at once");        }
        gate.reset();        System.out.println("After reset, broken: " + gate.isBroken());    }}
Output
Asha: TimeoutException
Bala: BrokenBarrierException
Broken: true
Late arrival: BrokenBarrierException at once
After reset, broken: false

What this code does

  • Only 2 of the 3 parties ever arrive (Chitra never comes). After 200 ms Asha's timed await gives up with TimeoutException, and that breaks the barrier.
  • Breaking is all or nothing: Bala, who was waiting with no timeout, is released with BrokenBarrierException instead of waiting forever. A later await() throws the same exception at once.
  • reset() repairs the barrier. Here no thread is waiting any more, so resetting is safe.

A barrier breaks when a waiting thread is interrupted, a timed await(timeout, unit) runs out of time, reset() is called while threads wait, or the barrier action throws. It is all or nothing. A broken barrier stays broken. Any later await() throws BrokenBarrierException at once, and isBroken() returns true. Call reset() to make it usable again, but only when no thread is waiting on it; often it is simpler to create a new barrier.

Because of this, await() throws two checked exceptions, InterruptedException and BrokenBarrierException, and the timed version also throws TimeoutException.

Find the bug

Find the barrier bug

Select the line that is wrong.

Three workers must meet, but one thread is missing from the count.

Round 1 of 3
If a barrier has more parties than threads that will ever arrive, plain await() waits forever. A timeout turns that hang into a clear exception.

Next step

Check your understanding

11 quick questions