0

For me the difference between CountDownLatch and CyclicBarrier is only that CyclicBarrier provides extra functionalities than CountDownLatch like you can execute a certain task when all threads would reach on a barrier point. You can find no of waiting threads and no of arrival threads in cyclic barrier. So it means we can use CyclicBarrier at all place where CountDownLatch is used. Please correct me if i am wrong. So why CountDownLatch is given in java. Why it is not deprecated if we can perform those functionalities with CyclicBarrier.

Indiver kumar
  • 15
  • 2
  • 8
  • This thread gives many details of use-cases which could be achieved only via CyclicBarrier and not using CountDownLatch : https://stackoverflow.com/questions/4168772/java-concurrency-countdown-latch-vs-cyclic-barrier – anish Mar 05 '18 at 20:55

1 Answers1

0

CyclicBarier waits for certain number of threads while CountDownLatch waits for certain number of events (one thread could call CountDownLatch.countDown() several times). CountDownLatch cannot be reused once opened. Also the thread which calls CountDownLatch.countDown() only signals that it finished some stuff. It doesn't block (and in CyclicBarrier.await() is blocking method) and could continue to do some other stuff.

From javadoc

A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

Ivan
  • 8,508
  • 2
  • 19
  • 30
  • Can you share me an small real world usecase where one thread would call countDown() multiple times. – Indiver kumar Mar 05 '18 at 14:35
  • @Indiverkumar not really a "real world" example as I do not work with `CountDownLatche/CyclicBarrier`. Your main thread needs to wait until completion of N tasks added into some collection. And it cannot spawn N threads (due to some restrictions). It could create `CountDownLatch` and each task will decrement `CountDownLatch`. After that main thread spawns let's say N/2 threads and feeds them this collection of tasks and waits for latch to open. – Ivan Mar 05 '18 at 15:06