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
5
4
3
2
1
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!...

11 comments:

  1. Useful information.I am actual blessed to read this article.thanks for giving us this advantageous information.I acknowledge this post.and I would like bookmark this post.Thanks

    Data Science training in Chennai
    Data science training in Bangalore
    Data science online training

    ReplyDelete
  2. Howdy, would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers, and I must say this blog loads a lot quicker than most. Can you suggest a good internet hosting provider at a reasonable price?
    Selenium Training institute in Bangalore
    Selenium Training institute in Bangalore

    ReplyDelete
  3. Greetings from Florida! I’m bored at work, so I decided to browse your site on my iPhone during lunch break. I love the information you provide here and can’t wait to take a look when I get home. I’m surprised at how fast your blog loaded on my cell phone.. I’m not even using WIFI, just 3G. Anyways, awesome blog!
    Data Science training in Chennai
    Data Science training in bangalore
    Data Science training institute in bangalore

    ReplyDelete
  4. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.

    Spring Boot and Micro services Training in Gurgaon
    Java Training in Gurgaon
    Java Framawork Training in Gurgaon

    ReplyDelete
  5. Excellent post. I learned a lot from this blog and I suggest my friends to visit your blog to learn new concept about technology.






    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete