Java CountDownLatch with Example

Learn the basics of CountDownLatch and how to use it in real-life applications, its methods and use it to control the flow of application.

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.

1. CountDownLatch class

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 the other set of threads completes their tasks.

For example, the application’s main thread wants to wait, till other service threads which are responsible for starting framework services have completed their tasks.

CountDownLatch works by having a counter initialized with a number of threads, which is decremented each time a thread completes its execution. When the count reaches zero, it means all threads have completed their execution, and the main thread waiting on the latch resumes 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 their tasks and count down the latch
- Main thread resume execution

2. How does a CountDownLatch work?

CountDownLatch 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 the latch should wait. This value can be set only once, and it provides no other mechanism to reset this count.

  • The first interaction with CountDownLatch is in main thread which is going to wait for other threads. This main thread must call, CountDownLatch.await() method immediately after starting other threads.
  • The execution will stop on latch.await() method till the time, other threads complete their execution.
  • Note that these N threads must have a reference to the latch object because they will need to notify the latch object that they have completed their task. This notification is done by CountDownLatch.countDown().
  • Each invocation of countDown() decreases the initial count set in the constructor, by 1. So, when all N threads have called this method, the count reaches to zero, and the main thread is allowed to resume its execution past await() method.

3. CountDownLatch Example

In this example, I have simulated an application startup class that 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 – This class is a Runnable and parent for all specific external service health checkers. This remove the code duplicacy and central control over the 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: This class extends BaseHealthChecker and needs to provide an implementation of verifyService() method. Similarly, DatabaseHealthChecker and CacheHealthChecker are same as NetworkHealthChecker 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: This class is the main startup class that initializes the latch and waits for 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 the 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);
  }
}

Program output is:

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

4. Possible Usages of CountDownLatch

Let’s try to identify some possible usage of CountDownLatch in real-life 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 a singleton. This can be done easily if we create a latch with initial count 1, and make wait all threads wait for the latch. A single call to countDown() method will resume execution for all waiting threads at the same time.
  2. Wait for N threads to complete before resuming execution: For example, an application start-up class wants 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 a different number of threads in each test phase, and try to create a deadlock.

5. Conclusion

In this tutorial, we learned the basics of CountDownLatch and how to use it in real-life applications. We learned important methods and how to use them to control the flow the application.

Happy Learning !!

Leave a Comment

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

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

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

    Reply
    • 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.

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

    Reply
  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

    Reply
    • 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.

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

        Reply
          • 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…

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

    Reply
    • 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]

      Reply
  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?

    Reply
    • 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.

      Reply
  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?

    Reply
    • 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();

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

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

      Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.