Search code examples
multithreadingconcurrencyjava.util.concurrentcountdownlatchcyclicbarrier

What is the purpose of await() in CountDownLatch?


I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.

I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?

Class CountDownLatchSimple:

public static void main(String args[]) {
  CountDownLatch latch = new CountDownLatch(3);
  Thread one = new Thread(new Runner(latch),"one");
  Thread two = new Thread(new Runner(latch), "two");
  Thread three = new Thread(new Runner(latch), "three");

  // Starting all the threads
  one.start(); two.start(); three.start();
  
}

Class Runner implements Runnable:

CountDownLatch latch;

public Runner(CountDownLatch latch) {
    this.latch = latch;
}

@Override
public void run() {
    System.out.println(Thread.currentThread().getName()+" is Waiting.");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    latch.countDown();
    System.out.println(Thread.currentThread().getName()+" is Completed.");
}

OUTPUT

two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.


Solution

  • CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.

    Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.

    So in your example it would make sense to call await() at the end of main() method:

    latch.await();
    

    Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.