Wednesday, September 12, 2012

CountDownLatch in java

The Java concurrency API provides a class that allows one or more threads to wait until a set of operations are made. It's the CountDownLatch class. This class is initialized with an integer number, which is the number of operations the threads are going to wait for. When a thread wants to wait for the execution of these operations, it uses the await() method.
This method puts the thread to sleep until the operations are completed. When one of these operations finishes, it uses the countDown() method to decrement the internal counter of the CountDownLatch class. When the counter arrives to 0, the class wakes up all the threads that were sleeping in the await() method.

  • This requirement is often needed in server side core java application.
  • You can implement the same functionality using wait() & Notify() mechanism but it require lot of code With CountDownLatch it can be done in few lines.

There is flexibility on number of Threads for which main Thread should wait. It can be one or n number of Threads. CountDownLatch work on the latch principle, means main Thread wait until Gate is open.One thread waits for n number of threads specified while creating CountDownLatch.

Usually main thread of application, which call CountDownLatch.await() will wait until count reached 0 or its interrupted by another thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they complete there job.

East Definition to remember CountDownLatch :
"Suppose a car can be lifted by 5 people so you will wait for all 5 to come. Then only you can lift the car."

Before looking into example, let have a look of countdownlatch class function:
  1. CountDownLatch(int count) : Creates an instance of CountDownLatch with the number of times the countDown() method must be called before the threads waiting with await()can continue execution.
  2. void await( ) : If the current count in CountDownLatch object is zero, it immediately returns; otherwise, the thread blocks until the countdown reaches zero. Can throw an InterruptedException
  3. void countDown( ) : Reduces the number of counts by one in this CountDownLatch object. If the count reaches zero, all the (a)waiting threads are released. If the current count is already zero, nothing happens.
  4. long getCount( ) : Returns the pending counts in this CountDownLatch object.

Example 1 :
For instance, before starting you main application may be you want to start few services such validation, db connection etc in such countdownlatch come into picture.
Here we consider 3 services that we need to start before main services. Please have a look at the code you will easily understood.

Output Sample:
validationis up
readis up
initial up
All Services is up

Example 2

Racing example

This example simulates the start of a running race by counting down from 5. It holds 3 runner thread to be ready to start in the start line of race and once the count down reaches 0, all the 3 runners start running.

Sample Output
tortise ready for countdown to start
hare ready for countdown to start
frog ready for countdown to start
Counter starting
tortise running....
hare running....
frog running....

How it works...
The CountDownLatch class has three basic elements:

  • The initialization value that determines how many events the CountDownLatch class waits for
  • The await() method, called by the threads that wait for the finalization of all the events
  • The countDown() method, called by the events when they finish their execution

When you create a CountDownLatch object, the object uses the constructor's parameter to initialize an internal counter. Every time a thread calls the countDown() method, the CountDownLatch object decrements the internal counter in one unit. When the internal counter arrives to 0, the CountDownLatch object wakes up all the threads that were waiting in the await() method.
There's no way to re-initialize the internal counter of the CountDownLatch object or to modify its value. Once the counter is initialized, the only method you can use to modify its value is the countDown() method explained earlier. When the counter arrives to 0, all the calls to the await() method return immediately and all subsequent calls to the countDown() method have no effect.

There are some differences with respect to other synchronization methods, which are as follows:

  • The CountDownLatch mechanism is not used to protect a shared resource or a  critical section. It is used to synchronize one or more threads with the execution of  various tasks.
  • It only admits one use. As we explained earlier, once the counter of CountDownLatch arrives at 0, all the calls to its methods have no effect. You have to create a new object if you want to do the same synchronization again.

Related Post

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...