Excellent question, Stanley! 🚧 Both CyclicBarrier
and CountDownLatch
are powerful synchronization tools in Java’s java.util.concurrent
package — but they serve different purposes and behave differently in key ways.
Let’s break them down and compare side by side.
🧩 Quick Summary:
Feature | CountDownLatch | CyclicBarrier |
---|---|---|
Purpose | Wait for other threads to finish | Wait until a group of threads is ready |
Reusable? | ❌ One-time use | ✅ Reusable (cyclic) |
Threads block on | await() (main thread waits) | await() (all threads wait for each other) |
When it proceeds | When count reaches zero | When all threads reach the barrier |
Can reset? | ❌ No | ✅ Yes (reset() method) |
Optional barrier action | ❌ No | ✅ Yes (Runnable runs once all arrive) |
📦 CountDownLatch
— Countdown & Go
Used when one or more threads must wait until other threads complete some work.
Example:
CountDownLatch latch = new CountDownLatch(3);
Runnable worker = () -> {
System.out.println(Thread.currentThread().getName() + " working...");
latch.countDown();
};
new Thread(worker).start();
new Thread(worker).start();
new Thread(worker).start();
latch.await(); // Main thread waits here until count = 0
System.out.println("All workers done. Proceeding...");
🧠 Key Points:
- The latch starts with a count.
- Each
countDown()
decrements the count. await()
blocks until count hits 0.- Not reusable — once it hits 0, it’s done forever.
🧱 CyclicBarrier
— Meet at the Checkpoint
Used when multiple threads must wait for each other to reach a common point.
Example:
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads reached the barrier!");
});
Runnable worker = () -> {
System.out.println(Thread.currentThread().getName() + " waiting at barrier");
barrier.await(); // Wait for 2 other threads
System.out.println(Thread.currentThread().getName() + " passed the barrier");
};
new Thread(worker).start();
new Thread(worker).start();
new Thread(worker).start();
🧠 Key Points:
- All threads call
await()
and wait for others. - Once all parties have arrived, the barrier releases them all.
- The optional Runnable barrier action runs just once when the last thread arrives.
- Reusable — can be used again after all threads pass the barrier.
🔁 Real-World Analogies
Situation | Tool | Analogy |
---|---|---|
Wait for workers to finish | CountDownLatch | Wait for 3 friends to finish chores before going to the movies |
Synchronize tasks in phases | CyclicBarrier | 3 friends wait at a checkpoint before continuing a hike together |
✅ When to Use What?
Scenario | Use |
---|---|
Main thread waits for tasks to complete | CountDownLatch |
Threads wait for each other at a common point | CyclicBarrier |
Need to reuse the barrier for multiple rounds | CyclicBarrier |
One-shot coordination (e.g., service startup) | CountDownLatch |