CountDownLatch in Java


CountDownLatch Java MultithreadingViews 1521

In this tutorial, we will discuss CountDownLatch in Java, its methods along with an example of how the CountDownLatch works.

CountDownLatch in Java

A CountDownLatch is one of the Java Concurrency utilities that makes all the threads wait until some mandatory operation is complete. It is a synchronization technique that initializes with a specific thread count. Whenever it calls the countDown() method, this count decreases. Also, each time the thread completes its execution, the counter decrements. When the count reaches 0, it means all the threads have completed their execution. The await() method blocks the main thread execution until the count reaches 0.

Java CountDownLatch methods

Below are the methods present in CountDownLatch in Java

MethodDescription
void await()It causes the current thread to wait until the countdown reaches 0.
boolean await(long timeout, TimeUnit timeunit)It causes the current thread to wait until the countdown reaches 0 or till the time elapses
void countDown()Decrements the count of the latch.
long getCount()Returns the current count
String toString()Returns the String representation of the latch

Working of Java CountDownLatch

The CountDownLatch class has only 1 constructor that initializes the thread count. This denotes the number of threads that are going to execute and wait for the latch. The main thread calls the await() method immediately after starting the threads.  This means the main thread waits until all threads complete their execution and the latch count becomes 0. The latch count decrements by 1 each time when a thread completes its execution. Once the count becomes 0, then the main thread resumes its execution.

CountDownLatch Applications

We can use the CountDownLatch in the below scenarios:

  • Achieve parallelism by executing multiple threads at the same time.
  • Wait for a certain execution to complete before starting the main thread execution
  • Deadlock prevention

CountDownLatch Example

Below is an example to demonstrate the working of a CountDownLatch in Java. In this example, we create a latch with 3 threads. We create 3 new threads for the Task class and execute them using the start() method. The Task class implements the Runnable interface which contains a run() method. This method has the actual thread execution. Whenever a thread completes its execution, it decrements the latch count by using the countDown() method.  We can notice that the statement in the main method executes only after all threads complete their execution. This is because we call the await() method after starting the thread. The await() method ensures that it resumes the main method execution only after all the threads complete its execution.

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

  public static void main(String[] args) {
    CountDownLatch cd = new CountDownLatch(3);
    
    Thread t1 = new Thread(new Task("Task1", cd));
    Thread t2 = new Thread(new Task("Task2", cd));
    Thread t3 = new Thread(new Task("Task3", cd));
    
    t1.start();
    t2.start();
    t3.start();
    
    try {
      cd.await();
      System.out.println("All tasks are executing...");
    }
    catch(InterruptedException e) {
      e.printStackTrace();
    }

  }

}

class Task implements Runnable {

  private CountDownLatch cl;
  private String name;
  
  Task(String name, CountDownLatch cl){
    this.name = name;
    this.cl = cl;
  }
  
  @Override
  public void run() {
    try {
      System.out.println("Start " + name);
      Thread.sleep(1000);
    }
    catch(InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Executing " + name);
    cl.countDown();
    
  }
  
}
Start Task1
Start Task3
Start Task2
Executing Task1
Executing Task3
Executing Task2
All tasks are executing...

 

Reference

Translate »