what's the difference between CyclicBarrier/CountDownLatch and join in Java?

coderz picture coderz · Feb 16, 2014 · Viewed 14.8k times · Source

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.

Answer

AnatolyG picture AnatolyG · Feb 18, 2014

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