Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between CountDownLatch and Cyclic Barriers? [duplicate]

I was reading through the java.util.concurrent API, and found that

  • CountDownLatch: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
  • CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

To me both seems equal, but I am sure there is much more to it.

For example, in CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier.

Is there any other difference between the two?
What are the use cases where someone would want to reset the value of countdown?

like image 659
daydreamer Avatar asked Nov 23 '22 07:11

daydreamer


2 Answers

There's another difference.

When using a CyclicBarrier, the assumption is that you specify the number of waiting threads that trigger the barrier. If you specify 5, you must have at least 5 threads to call await().

When using a CountDownLatch, you specify the number of calls to countDown() that will result in all waiting threads being released. This means that you can use a CountDownLatch with only a single thread.

"Why would you do that?", you may say. Imagine that you are using a mysterious API coded by someone else that performs callbacks. You want one of your threads to wait until a certain callback has been called a number of times. You have no idea which threads the callback will be called on. In this case, a CountDownLatch is perfect, whereas I can't think of any way to implement this using a CyclicBarrier (actually, I can, but it involves timeouts... yuck!).

I just wish that CountDownLatch could be reset!

like image 159
Kim Avatar answered Nov 25 '22 20:11

Kim


One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.

It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again.

For simple use cases - services starting etc... a CountdownLatch is fine. A CyclicBarrier is useful for more complex co-ordination tasks. An example of such a thing would be parallel computation - where multiple subtasks are involved in the computation - kind of like MapReduce.

like image 37
Jon Avatar answered Nov 25 '22 20:11

Jon