Java concurrency – CountDownLatch Example

As per java docs, CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. CountDownLatch concept is very common interview question in java concurrency, so make sure you understand it well. In this post, I will cover following points related to CountDownLatch in java concurrency.

Sections in this post:

What is CountDownLatch?
How CountDownLatch works?
Possible usages in real time applications
Example application
Common interview questions

What is CountDownLatch?

CountDownLatch was introduced with JDK 1.5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. This class enables a java thread to wait until other set of threads completes their tasks. e.g. Application’s main thread want to wait, till other service threads which are responsible for starting framework services have completed started all services.

CountDownLatch works by having a counter initialized with number of threads, which is decremented each time a thread complete its execution. When count reaches to zero, it means all threads have completed their execution, and thread waiting on latch resume the execution.

CountdownLatch
CountDownLatch Concept

Pseudo code for CountDownLatch can be written like this:

//Main thread start
//Create CountDownLatch for N threads
//Create and start N threads
//Main thread wait on latch
//N threads completes there tasks are returns
//Main thread resume execution

How CountDownLatch works?

CountDownLatch.java class defines one constructor inside:

	//Constructs a CountDownLatch initialized with the given count.
	public CountDownLatch(int count) {...}

This count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDownLatch provides no other mechanism to reset this count.

The first interaction with CountDownLatch is with main thread which is goind to wait for other threads. This main thread must call, CountDownLatch.await() method immediately after starting other threads. The execution will stop on await() method till the time, other threads complete their execution.

Other N threads must have reference of latch object, because they will need to notify the CountDownLatch object that they have completed their task. This notification is done by method : CountDownLatch.countDown(); Each invocation of method decreases the initial count set in constructor, by 1. So, when all N threads have call this method, count reaches to zero, and main thread is allowed to resume its execution past await() method.

Possible usages in real time applications

Let’s try to identify some possible usage of CountDownLatch in real time java applications. I am listing, as much i can recall. If you have any other possible usage, please leave a comment. It will help others.

  1. Achieving Maximum Parallelism : Sometimes we want to start a number of threads at the same time to achieve maximum parallelism. For example, we want to test a class for being singleton. This can be done easily if we create a CountDownLatch with initial count 1, and make wait all threads to wait of latch. A single call to countDown() method will resume execution for all waiting threads in same time.
  2. Wait N threads to completes before start execution: For example an application start-up class want to ensure that all N external systems are Up and running before handling the user requests.
  3. Deadlock detection: A very handy use case in which you can use N threads to access a shared resource with different number of threads in each test phase, and try to create a deadlock.

Example application using CountDownLatch

In this example, I have simulated an application startup class which starts N threads that will check for external systems and report back to latch, on which startup class is waiting. As soon as all services are verified and checked, startup proceeds.

BaseHealthChecker.java : This class is a Runnable and parent for all specific external service health checkers. This remove the code duplicacy and central control over latch.

public abstract class BaseHealthChecker implements Runnable {
	
	private CountDownLatch _latch;
	private String _serviceName;
	private boolean _serviceUp;
	
	//Get latch object in constructor so that after completing the task, thread can countDown() the latch
	public BaseHealthChecker(String serviceName, CountDownLatch latch)
	{
		super();
		this._latch = latch;
		this._serviceName = serviceName;
		this._serviceUp = false;
	}

	@Override
	public void run() {
		try {
			verifyService();
			_serviceUp = true;
		} catch (Throwable t) {
			t.printStackTrace(System.err);
			_serviceUp = false;
		} finally {
			if(_latch != null) {
				_latch.countDown();
			}
		}
	}

	public String getServiceName() {
		return _serviceName;
	}

	public boolean isServiceUp() {
		return _serviceUp;
	}
	//This methos needs to be implemented by all specific service checker
	public abstract void verifyService();
}

NetworkHealthChecker.java : This class extends BaseHealthChecker and needs to provide only implementation of verifyService() method. DatabaseHealthChecker.java and CacheHealthChecker.java are same as NetworkHealthChecker.java apart from their service names and sleep time.

public class NetworkHealthChecker extends BaseHealthChecker
{
	public NetworkHealthChecker (CountDownLatch latch)	{
		super("Network Service", latch);
	}
	
	@Override
	public void verifyService() 
	{
		System.out.println("Checking " + this.getServiceName());
		try 
		{
			Thread.sleep(7000);
		} 
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println(this.getServiceName() + " is UP");
	}
}

ApplicationStartupUtil.java : This clas is main startup class which initilizes the latch and wait of this latch till all services are checked.

public class ApplicationStartupUtil 
{
	//List of service checkers
	private static List<BaseHealthChecker> _services;
	
	//This latch will be used to wait on
	private static CountDownLatch _latch;
	
	private ApplicationStartupUtil()
	{
	}
	
	private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();
	
	public static ApplicationStartupUtil getInstance()
	{
		return INSTANCE;
	}
	
	public static boolean checkExternalServices() throws Exception
	{
		//Initialize the latch with number of service checkers
		_latch = new CountDownLatch(3);
		
		//All add checker in lists
		_services = new ArrayList<BaseHealthChecker>();
		_services.add(new NetworkHealthChecker(_latch));
		_services.add(new CacheHealthChecker(_latch));
		_services.add(new DatabaseHealthChecker(_latch));
		
		//Start service checkers using executor framework
		Executor executor = Executors.newFixedThreadPool(_services.size());
		
		for(final BaseHealthChecker v : _services) 
		{
			executor.execute(v);
		}
		
		//Now wait till all services are checked
		_latch.await();
		
		//Services are file and now proceed startup
		for(final BaseHealthChecker v : _services) 
		{
			if( ! v.isServiceUp())
			{
				return false;
			}
		}
		return true;
	}
}

Now you can write any test class to check the functionality of latch.

public class Main {
	public static void main(String[] args) 
	{
		boolean result = false;
		try {
			result = ApplicationStartupUtil.checkExternalServices();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("External services validation completed !! Result was :: "+ result);
	}
}

Output in console:

Checking Network Service
Checking Cache Service
Checking Database Service
Database Service is UP
Cache Service is UP
Network Service is UP
External services validation completed !! Result was :: true

Common interview questions

Be prepared to face these questions related to CountDownLatch in your next interview.

  • Explain the concept of CountDownLatch?
  • Difference between CountDownLatch and CyclicBarrier?
  • Give some example uses of CountDownLatch?
  • What are main methods CountDownLatch class has?

To Download the sourcecode of above example application follow given link.

Sourcecode Download
Reference

Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

32 thoughts on “Java concurrency – CountDownLatch Example”

  1. Mr Lokesh…excellent tutorial. How about a situation for CDL, where a group of tester wait for development team to start…and after some amount of development of the project is completed, testing team can start and development team will finish first… and testing team will also finish.. Correct me if I am wrong… Thank you..

  2. Possible usages of CountDownLatch in real time applications:
    Example : In a typical request processing scenario where multiple checks (tasks ) are happening sequentially. Here we can replace this with parallel processing by create multiple threads for each task and initialize the CountDownlatch with the same number, here we can call countDown() method each time when thread completes the execution, When count reaches to zero, it means all threads have completed,so that main thread wait until all threads to complete the execution.

  3. Hi Sir,Superb explanation,small doubt regarding Executor.in real time application,is it mandatory to shutdown the Executor?

    • The shutdown() method does one thing: prevents clients to send more work to the executor service. This means all the existing tasks will still run to completion unless other actions are taken.
      Let’s assume you have a console application which has an executor service running N tasks. If the user hits CTRL-C, you expect the application to terminate gracefully i.e. complete tasks at hand but do not accept new tasks.
      To summarize, calling shutdown() depends on usecase.

  4. There should be a small correction. The count is not actually the number of threads to wait, because a single thread can count down any number of time. Instead it should be as threads has to wait until count reaches to 0.

  5. Hi Lokesh,

    Nice explanation. But there are couple of doubts:-

    1) We can use CountDownLatch only when we know the number of thread to create (with fixed thread pool). am I correct?
    2) If we are using Thread Pool Executor, then what is the need of CountDownLatch, we can call executor.awaitTermination() to wait for all the threads to complete.

    Please help me to clarify above doubts.

    Thanks,
    Barun

    • 1) Yes
      2) awaitTermination() blocks until all tasks have completed execution “–after a shutdown request–“, or the timeout occurs, or the current thread is interrupted, whichever happens first. CountDownLatch is different thing.

      • Lokesh, could you explain little further.
        _latch.await() also seems to block the caller Thread till completion of all Threads.
        How is this different?

        • Hey Sanjeet seems to make some point.
          any clarification from any one.
          Lokesh, do you have a minute to comment?

          • CountDownLatch doesn’t require all threads calling countDown() to wait for the count to reach zero before proceeding (i.e. they call countDown() and move on to their individual execution path; No need to terminate any thread OR executor), it simply prevents primary thread (which called await() method) from proceeding past await() method until other threads could call countDown() method.

            executor.awaitTermination() is no where close to this concept. It tries to hold the shutdown of executor until all threads are done their complete execution path.

            Hope it helps 🙂

  6. Hi Lokesh,
    Regarding example “an application start-up class want to ensure that all N external systems are Up and running before handling the user requests.”

    My understanding is that here we are trying to say that…when ever we are rebooting the application server at that time ONLY countdown latches will be executing the below services i.e here in this example it is :
    NetworkHealthChecker
    DatabaseHealthChecker

    Is my understanding is correct? Plz let me know….Thanks…

  7. Hi Lokesh,
    Thanks for making us understaing multi threading concepts with so ease.
    I have one multi threading problem. Could you suggest me a solution.
    Question : There are multiple threads(can be more than thousand). Each thread has a numeric value i.e thread1 has ‘1’ , thread2 has ‘2’ and so on. I want these numbers(1,2,3,,……) to be printed in ascending order. How to do this. It looks to me that countdownlatch will be used here but don’t know how to implement this.

    Thanks in advance.

    • Hi Ranjeet,

      You can refer to below piece of code, if you can please improvise it!

      [Java]

      import java.util.concurrent.TimeUnit;
      import java.util.concurrent.atomic.AtomicInteger;

      public class NumberSequenceInThread {

      private Object monitor = new Object();
      private AtomicInteger numberOfThreads = new AtomicInteger(0);
      private AtomicInteger sequenceNumber = new AtomicInteger(1);

      public class Sequence implements Runnable{

      final int threadId;

      public Sequence(int threadId) {
      this.threadId = threadId;
      }

      @Override
      public void run() {
      numberOfThreads.incrementAndGet();
      System.out.println(“Starting the thread ” + this.threadId);
      printSequence();
      }

      private void printSequence() {
      try{
      while(true){
      TimeUnit.SECONDS.sleep(2);
      synchronized (monitor) {
      if(numberOfThreads.get() + 1 == sequenceNumber.get()){
      break;
      }
      if(threadId != sequenceNumber.get()){
      monitor.wait();
      }else{
      sequenceNumber.incrementAndGet();
      System.out.println(” Sequence number “+ threadId);
      monitor.notifyAll();
      }
      }
      }
      }catch(Exception e){
      e.printStackTrace();
      }

      }

      }

      public static void main(String[] args) {
      final int MAX_NUMBER = 20;
      NumberSequenceInThread num = new NumberSequenceInThread();
      Thread[] t = new Thread[MAX_NUMBER];

      for(int i=0 ; i < MAX_NUMBER ; i++){
      t[i] = new Thread(num.new Sequence(i+1));
      }
      for(int i=0 ; i < MAX_NUMBER ; i++){
      t[i].start();
      }
      }

      }

      [/Java]

  8. Hi Lokesh,
    Does the count in the constructor denotes the number of threads for which the latch should wait or is it the number of times countDown() method needs to be called before the main thread proceeds?

    • Using intelligently, you can achieve any desired result with basic method calls e.g. wait(), notify(), sleep() or join(). CountDownLatch provides you the ease so that you can concentrate on business, not on other tiny implementation details.

  9. This sample is a perfect solution for one of our requirement.I tried your source code, the main thread never gets terminated after execution of the program.What could be the reason for that?

    • use ExecutorService instead of Executor interface , after execute () call shutdown() to gracefully shutdown the ExecutorService and finally the main() will close.

      //Start service checkers using executor framework
      ExecutorService executor = Executors.newFixedThreadPool(_services.size());

      for(final BaseHealthChecker v : _services)
      {
      executor.execute(v);
      }

      executor.shutdown();

      //Now wait till all services are checked
      _latch.await();

  10. Hi Lokesh ,

    Can you explain CountDownlatch with simple program , i mean please do not use Executer framework.

  11. Please post some tutorial on java.concurrent package classes like CyclicBarrier,ReentrantLock,Semaphore etc…

  12. Hi’
    i have small doubt in hibernate please give me solution
    how to access last updated records in the data base?

    • If table colum have any timestamp or date field, then sort on this using criteria.
      session.createCriteria(Customer.class).addOrder(Order.desc(“lastUpdated”)).list();

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.