CountDownLatch in java

Hello Readers, In this article, we will learn about a very important topic of Java MultiThreading and Concurrency : CountDownLatch.

This topic is crucially important with respect to interviews on Java for experienced candidatesΒ  So let’s get started :

CountDownLatch :

CountDownLatch is a class present in the java.util.concurrent package. It was introduced in java 1.5Β  release. This utility is important for concurrent and synchronized behaviour of threads. This utility allows one or more thread to wait for other thread / threads to complete their operation.Β  CountDownLatch is initialised with a given count , which indicates the number of threads/services that needs to be completed for this thread to proceed further.

Important methods present in CountDownLatch class :

await() :

publicΒ voidΒ await() throws InterruptedException

The await() method blocks the current thread to process further until all the other threads do not invoke the countDown() method i.e. the current latch count does not reach to zero.

countDown() :Β 

publicΒ voidΒ countDown()

This method is invoked by the threads to decrement the count of the latch ,Β indicating that the service is completed and the waiting thread can resume its execution if the latch count is zero.

As soon as the count of latch becomes zero, await method return immediately.

Simple Illustrative example of CountDownLatch :

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class TestLatch {

// It is necessary to declare the InterruptedException using throws keyword in this method as the await() method thows this exception.

public static void main(String args[]) throws InterruptedException {

 

//We are creating here a thread pool.

ExecutorService es = Executors.newFixedThreadPool(2);

//Initializing the CountDownLatch with count as 3, means it will wait for three services to complete

CountDownLatch latch = new CountDownLatch(3);

es.execute(new TestLatch(latch));

 

latch.await();

 

es.shutdown();
}
}

class MyThread implements Runnable {

CountDownLatch latch;

 

MyThread(CountDownLatch c) {
latch = c;
new Thread(this);
}

 

public void run() {
for (int i = 0; i < 5; i++) {

latch.countDown();

}
}
}

Thanks for reading this article. I hope , you like it,

For any suggestions / feedback / question / clarification, Kindly post your comments in the below comment box.

Please subscribe our news letter and connect with social media accounts and don’t miss any articles.

Happy Reading!!!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

One comment

Leave a Reply