CKTIS / Java
CyclicBarrier: the barrier action and await
Synchronize a fixed number of threads between phases, run one shared action before they proceed, and distinguish timed from untimed waits.
Version: Java SE 21
Syntax
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
CyclicBarrier barrier = new CyclicBarrier(parties, barrierAction);
int arrivalIndex = barrier.await();
// Alternative for an arrival with a time limit:
int timedArrivalIndex = barrier.await(timeout, TimeUnit.SECONDS);In Java SE 21, java.util.concurrent.CyclicBarrier synchronizes a fixed number of threads at a phase boundary. CyclicBarrier(int,Runnable) takes a party count and an optional action. A count below 1 throws IllegalArgumentException. Passing null, or using CyclicBarrier(int), means there is no action.
The instance method CyclicBarrier.await has a no-argument form, await(), that waits for all parties without a timeout. The last thread to arrive runs the action once for that round, before any call returns successfully. The int result is the arrival index: parties - 1 for the first arrival and 0 for the last. Code in an if (barrier.await() == 0) branch runs after the barrier has released the group, so it cannot replace an action that must finish before peers proceed.
Work before await() happens-before the barrier action, and the action happens-before work in other threads after their corresponding successful return. After a successful round, the same barrier is automatically ready for another one; no reset() is needed.
await(long timeout, TimeUnit unit) limits the wait. If it expires, that caller gets TimeoutException and the barrier breaks. If await handles an interrupt while the thread's round is still current and the barrier is unbroken, it throws InterruptedException, clears the thread's interrupt status, and breaks the barrier. If the round instead completes successfully and the barrier advances to the next round before the waiter handles the interrupt, await can return the arrival index with the thread's interrupt status set (restored if necessary). An exception from the action propagates to the last arriver and breaks the barrier too. Other waiters generally get BrokenBarrierException, as do calls on an already broken barrier. reset() restores the initial state but makes current waiters fail with BrokenBarrierException, so coordinate recovery.
Examples
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
public class BarrierPhases {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int parties = 3;
var barrier = new CyclicBarrier(parties,
() -> System.out.println("4: Barrier action"));
Callable<Void> worker = () -> {
System.out.println("Phase 1");
barrier.await();
System.out.println("Phase 2");
return null;
};
try (var pool = Executors.newFixedThreadPool(parties)) {
for (var result : pool.invokeAll(List.of(worker, worker, worker))) {
result.get();
}
}
}
}Result
Phase 1 Phase 1 Phase 1 4: Barrier action Phase 2 Phase 2 Phase 2
Three tasks use three pool threads and cross the barrier just once. `4: Barrier action` is the fourth output line, not a fourth party. Each task prints the same text within a phase, so thread scheduling does not change the output.
Related lessons
- Java · Lesson 34 · Advanced · Version: 2