CountDownLatch Example in Java

By | June 23, 2020

In this post, We will talk and learn about CountDownLatch in Java using an Example.

CountDownLatch  is a synchronization helping class that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch has to initialize with a given count. The await method blocks until and unless the current count reaches to zero due to invocations of the countDown() method every time, after that all waiting threads are released and any subsequent invocations of await return immediately.

This is a one-shot phenomenon that in CountDownLatch  the count cannot be reset. If you need a version that resets the count then consider using a CyclicBarrier.

The CountDownLatch initialized with count N at the time of instantiation and it can be used to make one thread wait until N threads have completed some action or some action has been completed N number of times.

Complete source code:

DevTeam.java 

QATeam.java

AssignTaskManagerTest.Java

Output of this Program:

Task assigned to development team dev-A
Task assigned to development team dev-B
Task finished by development team dev-A
Task finished by development team dev-B
Task assigned to QA team
Task finished by QA team

You May Also Like:

How would you round a double value to certain decimal Precision and Scale ?
What is BlockingQueue? How can we implement Producer and Consumer problem using Blocking Queue?
How to get number of available processors in Java ?

That’s all about  CountDownLatch Example in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *