JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label CountDownLatch. Show all posts
Showing posts with label CountDownLatch. Show all posts

Difference between CountDownLatch and CyclicBarrier in java

8:32 AM
Lets see differences between CountDownLatch and CyclicBarrier. CountDownLatch vs CyclicBarrier Parameter CountDownLatch CyclicBarrier Reuse It can not be reused once count reaches 0 It can be reinitialized once parties reaches to 0, so it can reused Method  It calls countDown() method to reduce the counter It calls await() method to reduce the counter. Common Event It can not trigger common event when count reaches 0 It can trigger common event (Runnable) once reaches to a barrier point.  Constructor :CyclicBarrier(int parties, Runnable barrierAction) Constructor CountDownLatch(int count) CyclicBarrier(int parties)

CountDownLatch in java

8:30 AM
CountDownLatch is synchronisation aid that allow one or more threads to wait until set of operations being performed in other threads completes. So in other words, CountDownLatch waits for other threads to complete set of operations. CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it’s interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation. So count is reduced by 1 whenever latch.countDown() method get called, so  if count is  n  that means count can be used as  n  threads have to complete some action or some action have to be completed  n  times. One of disadvantage of CountDownLatch is you can not reuse it once count is zero. For that ,you need to use CyclicBarrier. For example: Below diagram will make you clear. It is an  example  h...

.