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!...


  1. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    Advanced AWS Training in Bangalore | Best Amazon Web Services Training Institute in Bangalore
    Advanced AWS Training Institute in Pune | Best Amazon Web Services Training Institute in Pune
    Advanced AWS Online Training Institute in india | Best Online AWS Certification Course in india
    AWS training in bangalore | Best aws training in bangalore

  2. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

  3. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

  4. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

  5. Great Article… I love to read your articles because your writing style is too good,
    its is very very helpful for all of us and I never get bored while reading your article because,
    they are becomes a more and more interesting from the starting lines until the end.
    Java training in Annanagar
    Java training in Chennai
    Java training in Chennai
    Java training in Electronic city
    Java training in Marathahalli

  6. Thanks For Sharing The Information The Information shared Is Very Valuable Please Keep Updating Us Time Just Went On reading The Article Aws Online Course Python Online Course Data Online Course Hadoop Online Course

  7. 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

  8. 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

  9. 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

  10. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

  11. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article Python Online Course Hadoop Online Course Aws Online Course Data Science Online Course