Sobes.tech
Middle

What are the differences between CyclicBarrier and CountDownLatch?

sobes.tech AI

Answer from AI

CountDownLatch:

  • Used for one or more threads to wait for the completion of other threads.
  • Initialized with a counter that decreases when countDown() is called.
  • Waiting threads are blocked by calling await().
  • When the counter reaches zero, all waiting threads are released.
  • Threads can call await() multiple times, but the counter does not reset.

CyclicBarrier:

  • Used to synchronize a group of threads at a certain point ("barrier").
  • Initialized with the number of threads that must reach the barrier.
  • Threads block by calling await(), until all expected threads reach the barrier.
  • Once all threads reach the barrier, they are released.
  • The barrier is "cyclic" - it can be reused after all threads have passed through it.
  • It can have an optional action performed by one of the threads after all threads reach the barrier but before they are released.

Comparison table:

Characteristic CountDownLatch CyclicBarrier
Purpose One/multiple wait for others Group of threads synchronize
State reset No Yes
Threads waiting Those calling await() All that must reach the barrier
Optional action No Yes