Introduction
The Java CyclicBarrier class joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent package designed by Doug Lea. It is a synchronisation aid that lets a fixed number of threads wait for each other at a common barrier point, then releases them all at once. Unlike CountDownLatch, which is one-shot, a CyclicBarrier is reusable: once the parties have crossed the barrier, it resets automatically and can be used again for the next phase. This cyclic behaviour is the source of the "Cyclic" in its name.
For a Java learner, the java cyclicbarrier primitive is the right tool whenever you have a parallel computation that splits naturally into phases. Each thread does its portion of one phase, waits at the barrier, and once all threads arrive, they all proceed to the next phase. The classic use cases are matrix multiplication, parallel iterative solvers, simulation steps, and pipeline stages. This post walks through the barrier mechanics, demonstrates a two-phase matrix computation, and shows how to use the optional barrier action that runs once per cycle.
What is Java CyclicBarrier?
The Java CyclicBarrier is a thread synchronisation aid constructed with a positive integer parties. When a thread calls await on the barrier, it blocks until parties threads have called await; then all are released together. After release, the internal counter resets to parties, so the same barrier can be reused for the next phase. Optionally, you can supply a Runnable that runs once per cycle, after the last thread arrives but before any thread is released; this is the barrier action, commonly used to combine the partial results computed in the phase.
Conceptually, CyclicBarrier is distinct from CountDownLatch in two important ways. First, CountDownLatch is one-shot: once its counter reaches zero, it stays at zero forever, and further await calls return immediately. CyclicBarrier resets after each cycle, so the same instance can coordinate many phases. Second, CountDownLatch separates the awaiters from the counters: any thread can count down, and any thread (or the same thread) can await. CyclicBarrier fuses those roles: the threads that count down are exactly the threads that await. This makes it the natural fit when the same group of workers proceeds together phase by phase.
CyclicBarrier also differs from Phaser (Java 7 and later), which supports dynamic registration of parties and a more general phase numbering scheme. CyclicBarrier is simpler, has a fixed party count, and is the right choice when you know the worker count up front and it does not change.
How Java CyclicBarrier Works - Step by Step
Step 1: Construction. You write new CyclicBarrier(3) to create a barrier for three threads, or new CyclicBarrier(3, () -> System.out.println("phase done")) to attach a barrier action. The action runs on the thread that arrives last (the one whose await call completes the count); this thread runs the action before any thread is released.
Step 2: Threads call await. Internally, a generation counter tracks the current cycle. Each await call decrements the count of remaining parties; if the count is still positive after the decrement, the calling thread parks on an internal lock until notified.
Step 3: The last arrival. When the last thread calls await, the count reaches zero. If a barrier action is present, the last-arriving thread executes it synchronously, while the other parties remain parked. After the action returns (or if there is no action), all waiting threads are signalled, the count is reset to parties, the generation is bumped, and all threads resume from await.
Step 4: Reuse for the next phase. Because the count and generation reset, the same barrier instance is now ready for another cycle. Threads call await again on the next phase, and the protocol repeats. This is why CyclicBarrier is preferred for iterative algorithms.
Step 5: Exceptions and interruption. If any thread is interrupted while waiting on await, the barrier is broken: it enters a "broken" state, the interrupted thread throws InterruptedException, all other waiters throw BrokenBarrierException, and the barrier can only be reused after reset is called or all parties have left. If the barrier action throws, the same broken state occurs. A timeout on await(long, TimeUnit) works the same way: a timeout breaks the barrier.
Java Program for CyclicBarrier
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierDemo {
static final int N = 3; // number of worker threads
static final int PHASES = 2; // number of computation phases
static final int SIZE = 6; // shared array size
static int[] data = new int[SIZE];
static long phaseSum = 0;
public static void main(String[] args) throws InterruptedException {
// Barrier with a side action: combine partial sums and print
CyclicBarrier barrier = new CyclicBarrier(N, () -> {
System.out.println("phase complete, combined sum = " + phaseSum);
phaseSum = 0; // reset for the next phase
});
ExecutorService pool = Executors.newFixedThreadPool(N);
for (int t = 0; t < N; t++) {
final int id = t;
pool.submit(() -> {
for (int phase = 0; phase < PHASES; phase++) {
// Phase work: each thread writes two cells
int start = id * (SIZE / N);
int end = start + (SIZE / N);
int partial = 0;
for (int i = start; i < end; i++) {
data[i] = (id + 1) * 10 + i + (phase * 100);
partial += data[i];
}
synchronized (CyclicBarrierDemo.class) {
phaseSum += partial;
}
System.out.println("worker " + id + " phase " + phase
+ " partial=" + partial);
try {
barrier.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} catch (BrokenBarrierException e) {
return;
}
}
});
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("all phases done");
}
}
Code Explanation - Line by Line
The class declares the barrier parameters as static finals: N is the number of worker threads, PHASES is the cycle count, and SIZE is the size of the shared array. The data array is the shared state each thread writes a slice of, and phaseSum is a shared accumulator for the barrier action. Making these static keeps the demo small; in production code you would pass them in via instance fields or constructor parameters.
The CyclicBarrier is constructed with N as the party count and a Runnable lambda as the barrier action. The Runnable reads phaseSum, prints the combined value, and zeroes it for the next phase. The action runs on the last-arriving thread only, before any thread is released from await; this guarantees that the partial sums written by the other threads are visible to the action, because the await call's internal lock acts as a memory barrier.
The main method submits N tasks to a fixed thread pool. Each task loops over PHASES phases. Inside the loop, the worker computes its slice of indices and writes the array. The partial sum for the slice is added to phaseSum under the class monitor (synchronised block). The worker then prints its partial and calls await. At most one worker has finished its partial when the others call await; that last worker runs the barrier action before any worker resumes, ensuring phaseSum reflects the full set of partials for that phase.
After await returns, all workers proceed to the next phase together. The barrier count has reset, so the second phase is identical in form. After both phases finish, each task returns. The main thread shuts down the pool and waits up to 5 seconds for completion, then prints the final confirmation. The output shows two barrier actions, one per phase, demonstrating the cyclic reuse of the same barrier instance.
Sample Input and Output
Input: N=3 workers, PHASES=2 phases, SIZE=6 array Output (order of worker lines may vary): worker 0 phase 0 partial=23 worker 1 phase 0 partial=44 worker 2 phase 0 partial=65 phase complete, combined sum = 132 worker 0 phase 1 partial=123 worker 1 phase 1 partial=144 worker 2 phase 1 partial=165 phase complete, combined sum = 432 all phases done
The combined sum after phase 0 is the sum of the three partial values (23 + 44 + 65 = 132), and the sum after phase 1 is 123 + 144 + 165 = 432. The barrier action runs exactly once per phase, even though all three threads call await; it is the last-arriving thread that runs the action.
Common Mistakes to Avoid
Mistake 1: Using a CyclicBarrier with the wrong party count. If you build the barrier for N parties but only N-1 threads call await, the barrier never trips and the program hangs. Double-check that the party count matches the number of threads that will actually await.
Mistake 2: Forgetting that the barrier action runs on the last-arriving thread. Code that uses the action to combine partial sums must make sure that those partials have been published with proper visibility. The barrier's internal lock makes the await call a happens-before edge, so values written before await are visible to the action and to other threads after they resume; values written after await are not.
Mistake 3: Treating CyclicBarrier as one-shot. If your phases only need one cycle, CountDownLatch is the lighter and clearer choice. Use CyclicBarrier only when the same group of threads will cross the barrier multiple times.
Mistake 4: Letting an exception escape the barrier action. If the Runnable supplied to the constructor throws, the barrier is broken permanently for that cycle, every other waiter gets a BrokenBarrierException, and the same instance cannot be reused until reset. Always wrap risky logic in the action with try-catch and surface errors through a shared error flag.
Real-World Applications
Parallel matrix computation. In scientific computing, iterative solvers like Jacobi or Gauss-Seidel relaxation split a grid among worker threads; each worker computes its slice of the new grid from the old grid, waits at a barrier, then swaps buffers and iterates. CyclicBarrier is the natural primitive for that swap step.
Pipeline stages. A four-stage image pipeline (decode, resize, watermark, encode) can be modelled as four barriers, each releasing its stage threads together before the next stage starts. The cyclic nature allows the pipeline to drain many images through the same barriers.
Build systems. Parallel build tools like Gradle's worker API use barriers at task boundaries to coordinate the fan-out of independent tasks and the fan-in of their results.
Game servers. Per-frame simulation in a game loop often uses a barrier between the "update" phase (AI, physics) and the "render" phase so that renderers see a consistent snapshot. The barrier resets every frame.
Fork-join parallel iteration. Whenever a problem has a fixed worker count and a fixed phase count, CyclicBarrier is the right tool. For variable party counts or advanced phase numbering, use Phaser instead.
Conclusion
CyclicBarrier is the canonical way to coordinate a fixed group of threads through multiple phases, with optional one-shot side actions that combine partial results at each cycle. It is reusable, simple, and fits iterative parallel algorithms naturally. The next topics worth studying are Phaser (for dynamic party counts and richer phase numbering), CountDownLatch (for one-shot fan-in coordination), and the ExecutorService API that hosts the worker threads used with CyclicBarrier.
Comments
Comments
Post a Comment