Q 61
Medium
What is CyclicBarrier and how does it differ from CountDownLatch?
Answer
CyclicBarrier is a reusable barrier where a set of threads must all wait for each other to reach a common barrier point (await()) before proceeding. Unlike CountDownLatch (which counts events and cannot be reset), CyclicBarrier can be reset and reused across multiple phases.
Explanation
CyclicBarrier can execute an optional barrier action runnable as soon as the last thread arrives at the barrier.
Code Example
Java
CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("Phase complete!"));
Runnable task = () -> {
System.out.println("Arrived at barrier");
try { barrier.await(); } catch (Exception e) {}
};
for (int i = 0; i < 3; i++) new Thread(task).start();
Reference:
Java Multithreading & Concurrency