CountDownLatch in java

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

One Comment on “CountDownLatch in java”

Leave a Reply

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