Thursday 15 May 2014

CountDownLatch in java is a kind of synchronizer which allows one Trhead to wait for one or more theads before it starts processing.

Countd=DownLatch Works in latch principle, main thread will wait until Gate is open. One thread waits for n number of threads specified while creating CountDownLatch in java.

e.g. final countDownLatch latch = new CountDownLatch(3);

Here we set the counter to 3.

Any thread usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another Thread. All other threads are required to do count down by calling CountDownLatch.countDow() once they are completed or ready to the job. as soon as count reaches zero, the Thread awaiting starts running.

Here the countis get decremented by CountDownLatch.countDown() method.

The Thread which calls the await() method will wait until the initial count reaches to zero.

To make count zero other threads need to call the countDown() method. Once the count become zero the thread which invoked the await() method will resume (start its execution).

The disadvantage of CountDownLatch is that it's not reusable. once the count become zero it is no longer usable.