Multithreading
CyclicBarrier
Coordinate cyclic, reusable barrier checkpoints in parallel algorithms.
Interview: Compares CyclicBarrier vs CountDownLatch and details how cyclic barriers run barrier actions.
A CyclicBarrier is a synchronization aid that allows a set of threads to wait for each other to reach a common barrier point. Unlike CountDownLatch, it can be reset and reused recursively.
Core Idea
A barrier halts threads at await() until N threads arrive. Once all arrive, the barrier opens, optionally running a action, then resets.
Why It Matters
Perfect for multi-phase calculation algorithms where sub-tasks must complete Phase 1 before any can start Phase 2.
Interview Lens
Tests differences between CyclicBarrier and CountDownLatch, and how to handle BrokenBarrierException.
CyclicBarrier vs. CountDownLatch
Let's compare these two coordination utilities:
- Reusability: CyclicBarrier can be reset and reused (hence "cyclic"). CountDownLatch is a one-shot utility.
- Waiting Threads: In CyclicBarrier, the worker threads call
await()to block themselves. In CountDownLatch, the workers callcountDown()(non-blocking) and a coordinator thread callsawait(). - Barrier Action: CyclicBarrier allows running an optional callback task when the barrier opens.
Code Walkthrough
This program demonstrates worker threads syncing at a barrier checkpoint before completing their tasks.
import java.util.concurrent.CyclicBarrier;public class CalculationPipeline { public static void main(String[] args) { Runnable barrierAction = () -> System.out.println("All workers arrived! Merging data..."); CyclicBarrier barrier = new CyclicBarrier(3, barrierAction);
Runnable worker = () -> { try { System.out.println(Thread.currentThread().getName() + " working on Phase 1..."); Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " waiting at checkpoint..."); barrier.await(); // Block until all 3 workers arrive
System.out.println(Thread.currentThread().getName() + " working on Phase 2..."); } catch (Exception e) { // Handle BrokenBarrierException or InterruptedException } };
new Thread(worker, "Worker-1").start(); new Thread(worker, "Worker-2").start(); new Thread(worker, "Worker-3").start(); } }
Interview-Relevant Information
Q: What causes a BrokenBarrierException?
Answer: A BrokenBarrierException is thrown if one of the waiting threads is interrupted or timed out while waiting at the barrier. If this happens, the barrier is marked as "broken", and all other waiting threads immediately wake up and throw BrokenBarrierException to prevent deadlock.
Quick Checklist
How do you configure a barrier action? What is a BrokenBarrierException? If yes, you understand CyclicBarrier.
Use Cases
Dividing numerical simulation grid steps across threads and merging results before moving to the next iteration.
Multi-stage map-reduce calculations.
Common Mistakes
Specifying a thread count size larger than the actual active thread count, deadlocking the system because the barrier never opens.
Ignoring BrokenBarrierException, failing to handle cleanup of other threads in the calculation.