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

45 comments:

  1. Replies
    1. Great Article android based projects

      Java Training in Chennai

      Project Center in Chennai

      Java Training in Chennai

      projects for cse

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

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

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

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

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

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

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

    ReplyDelete
  8. 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
  9. 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
  10. 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
  11. 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

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

    ReplyDelete
  13. An overwhelming web journal I visit this blog, it's unfathomably amazing. Unusually, in this present blog's substance made inspiration driving truth and reasonable. The substance of data is enlightening
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  14. Wow it is really wonderful and awesome thus it is veWow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    python training in bangalore

    python courses in bangalore

    python classes in bangalore

    python training institute in bangalore

    python course syllabus

    best python training

    python training centers

    ReplyDelete
  15. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

    aws training in bangalore

    aws courses in bangalore

    aws classes in bangalore

    aws training institute in bangalore

    aws course syllabus

    best aws training

    aws training centers

    ReplyDelete
  16. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ReplyDelete
  17. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  18. I'm highly dazed with the quality of the content which you have penned down. This is a splendid article! Your article has all the necessary information on the respective topic.

    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata

    ReplyDelete
  19. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    data science interview questions

    ReplyDelete
  20. I am highly overwhelmed to read this perfect piece of writing. It has really enthused me to read more on this topic.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

    ReplyDelete
  21. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

    Devops Training in USA

    Hadoop Training in Hyderabad

    Python Training in Hyderabad

    ReplyDelete
  22. 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
  23. Highly appreciable regarding the uniqueness of the content. This perhaps makes the readers feels excited to get stick to the subject. Certainly, the learners would thank the blogger to come up with the innovative content which keeps the readers to be up to date to stand by the competition. Once again nice blog keep it up and keep sharing the content as always.
    Data Science Training

    ReplyDelete
  24. Thanks for posting the best information and the blog is very helpful.python course in Bangalore

    ReplyDelete
  25. Thanks for posting the best information and the blog is very helpful.data science interview questions and answers

    ReplyDelete
  26. 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
  27. This comment has been removed by the author.

    ReplyDelete
  28. I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara

    ReplyDelete
  29. https://ravivarma.in/invideo-review/

    ReplyDelete
  30. Extraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Data Science Training

    ReplyDelete
  31. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    Data Science Certification in Bhilai

    ReplyDelete
  32. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data analytics course in delhi

    ReplyDelete