CKTIS / Java
CyclicBarrier — cyclic thread synchronization
CyclicBarrier synchronizes a fixed number of participants at successive phase boundaries. Calling await() waits for the others; an optional action combines results before the next phase begins.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
new CyclicBarrier(int parties)
new CyclicBarrier(int parties, Runnable barrierAction)
int await() throws InterruptedException, BrokenBarrierException
int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutExceptionCyclicBarrier from java.util.concurrent is a reusable synchronization point. Unlike the one-shot CountDownLatch, it supports successive cycles. Its constructor requires parties >= 1.
CyclicBarrier.await() waits for all participants and returns an arrival index: the last receives 0. The last thread runs the optional action before releasing the others. Writes before await() are visible to the action, whose actions are visible after participants return successfully.
Interruption or timeout breaks the barrier: the affected participant receives InterruptedException or TimeoutException, while other waiting participants normally receive BrokenBarrierException. reset() also disrupts waiting; recovery requires coordination. Ensure all participants can run to avoid indefinite waiting.
The example uses two threads and two cycles. Each thread writes its own array element; the action prints the sum. Scope: Java SE 21; the production runtime has not been attested.
Examples
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class BarrierDemo {
public static void main(String[] args) throws InterruptedException {
int[] values = new int[2];
CyclicBarrier barrier = new CyclicBarrier(2,
() -> System.out.println(values[0] + values[1]));
Thread[] workers = new Thread[2];
for (int i = 0; i < workers.length; i++) {
final int index = i;
workers[i] = new Thread(() -> {
try {
for (int phase = 1; phase <= 2; phase++) {
values[index] = (index + 1) * phase;
barrier.await();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (BrokenBarrierException e) {
throw new IllegalStateException(e);
}
});
workers[i].start();
}
for (Thread worker : workers) {
worker.join();
}
}
}Result
3 6
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.