Java-CountDownLatch

CountDownLatch

The CountDownLatch is a very simple synchronization utility that allows any number of threads to block, waiting for a countdown value to reach 0 before being “released” to continue their activities. The CountDownLatch is initialized with the count when constructed. Thereafter, threads may block using the await() method or block for a limited period of time using the timed wait version of await(). Any running thread may decrement the counter at any time, whether threads are blocked or not. Once the counter reaches 0, all waiting threads unblock and continue. Thereafter, any calls to await() do not block. The count cannot be reset.

CountDownLatch

CountDownLatch has the following constructor :

CountDownLatch

Here, num specifies the value of the counter. To wait on the latch, a thread calls await( ) methods :

CountDownLatch

The first form waits until the count associated with the invoking CountDownLatch reaches zero. The second form waits only for the period of time specified by wait. The units represented by wait are specified by tu, which is an object the TimeUnit enumeration. It returns false if the time limit is reached and true if the countdown reaches zero. To decrement the counter value, call the countDown( ) method. Each call to countDown( ) decrements the count associated with the invoking object. The getCount() method is used to get the counter value.

Program

CountDownLatch output

Program Explanation

This program uses a CountDownLatch called cdl is created with an initial count of five. Next, an instance of MyClass is created, which begins execution of a new thread. Notice that cdl is passed as a parameter to MyClass’s constructor and stored in the latch instance variable. Then, the main thread calls await( ) on cdl, which causes execution of the main thread to pause until cdl’s count has been decremented five times.

Inside the run( ) method of MyClass, a loop is created that iterates five times. With each iteration, the countDown( ) method is called on latch, which refers to cdl in main( ). After the fifth iteration, the counter reaches 0, which allows the main thread to resume. CountDownLatch is a powerful yet easy-to-use synchronization object that is appropriate whenever a thread must wait for one or more events to occur.

Program Source

import java.util.concurrent.CountDownLatch;

class MyClass extends Thread {

    CountDownLatch cdl;

    MyClass(CountDownLatch cd) {

        cdl = cd;
    }

    public void run() {
        for (int i=0;i<5;i++) {             
        try {                 
             Thread.sleep(1000);                 
             System.out.println(Thread.currentThread().getName() + "->"+i);
             cdl.countDown();
            } catch (InterruptedException ie){}
        }
    }
}

public class Javaapp {

    public static void main(String[] args) {

        CountDownLatch cdl = new CountDownLatch(5);

        MyClass myc = new MyClass(cdl);
        myc.start();
        try {
            System.out.println("Main thread waiting.....");
            cdl.await();
            System.out.println("Resuming main thread.....");
            for (int i=5;i<10;i++) {                 
                 Thread.sleep(1000);                 
                 System.out.println("Main thread->"+i);
            }
        } catch (InterruptedException ie) {}
    }
}

Leave a Comment