Java CountdownLatch Class

Category: Java   Tags: Java, Java Thread, Java MultiThread, Thread Synchronization, Immutable Objects, Java Concurrent Collection

A CountDownLatch is initialized with the given number of events that must occur before releasing the latch. Each time an event happens, the count is decremented and when the count is zero, the latch opens. CountDownLatch has one constructor:

                                CountDownLatch(int count)

count is the number of events that must occur to open the latch.


CountDownLatch class has below methods:

                            await(long timeout, TimeUnit unit)

First form causes the current thread to wait until the latch reaches to zero. Second form also causes the current thread to wait until the latch reaches to zero or specified timeout period of time has passed.


Every time it decrements the count of the latch. Once count reaches zero, all waiting threads are released.

Here is one simple Java program to show you how CountDownLatch works:

                            package com.tutorial.javabasic;

                            import java.util.concurrent.CountDownLatch;

                            class SampleThread implements Runnable {

                                private CountDownLatch countDownLatch;

                                SampleThread(CountDownLatch latch) {
                                    countDownLatch = latch;
                                    new Thread(this).start();

                                public void run() {
                                    for (int i = 1; i <= 4; i++) {
                                        System.out.println("Event" + i);


                            public class JavaCountDownLatchExample {

                                public static void main(String s[]) {
                                    CountDownLatch semaphore = new CountDownLatch(4);
                                    new SampleThread(semaphore);
                                    try {
                                    } catch (InterruptedException ex) {
                                    System.out.println("All event executed!");


                            All event executed!

Here CountDownLatch is initiated with four events. With every iteration of loop CountDownLatch is decremented and as soon as it is decremented four times, immediate statement after semaphore.await(); is executed.