Question

what's the difference between CyclicBarrier/CountDownLatch and join in Java? What's the advantage of CyclicBarrier and CountDownLatch? In my opinion, just use join we can wait for a thread complete its execution.

Was it helpful?

Solution

Yes, "t.join()" makes the current thread waiting for "t" thread is finished and we can prepare a chain of threads when a thread is waiting for some other. But sometimes CountDownLatch/CyclicBarrier are more convenient.

First of all, CountDownLatch/CyclicBarrier don't require all working threads should be finished. The threads can be running all the time the application is running. They just let us say that "some work" is done a number of times. Moreover, if we have N jobs and M threads and N > M, some threads can do a job several times until their common barier N is 0. This example shows that CountDownLatch/CyclicBarrier are very useful primitives to share N tasks between M threads.

Also, to use join(), each thread should have a reference to another thread to call join(). It makes your code a bit dirty especially when you have more than 2 working threads. Sharing of one instance of CountDownLatch/CyclicBarrier looks more clear.

The main difference between CyclicBarrier and CountDownLatch is that CyclicBarrier is reusable and CountDownLatch is not. You can reuse CyclicBarrier by calling reset() method which resets the barrier to its initial state.

CountDownLatch is good for one time event like application/module start-up time and CyclicBarrier can be used to in case of recurrent event e.g. concurrently (re-)calculating each time when the input data changed.

You can find some good examples at:

http://javarevisited.blogspot.sg/2012/07/countdownlatch-example-in-java.html http://javarevisited.blogspot.ru/2012/07/cyclicbarrier-example-java-5-concurrency-tutorial.html

OTHER TIPS

join() waits for one thread to complete. CountDownLatch.await() allows N threads to wait until the countdown reaches 0. It can be used to make sure N threads start doing something at the same time (starting a race, for example), or to wake up another thread once N threads have reached a given point (the end of a race, for example).

The javadoc gives a concrete example of the use of CountDownLatch. Read it.

CyclicBarrier is similar to CountDownLatch, but allows for regular coordination points.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top