Java.Multithreading.What is the difference between CyclicBarrier and CountDownLatch?

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:

FeatureCountDownLatchCyclicBarrier
PurposeWait for other threads to finishWait until a group of threads is ready
Reusable?❌ One-time use✅ Reusable (cyclic)
Threads block onawait() (main thread waits)await() (all threads wait for each other)
When it proceedsWhen count reaches zeroWhen 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

SituationToolAnalogy
Wait for workers to finishCountDownLatchWait for 3 friends to finish chores before going to the movies
Synchronize tasks in phasesCyclicBarrier3 friends wait at a checkpoint before continuing a hike together

✅ When to Use What?

ScenarioUse
Main thread waits for tasks to completeCountDownLatch
Threads wait for each other at a common pointCyclicBarrier
Need to reuse the barrier for multiple roundsCyclicBarrier
One-shot coordination (e.g., service startup)CountDownLatch
This entry was posted in Без рубрики. Bookmark the permalink.