Provide Best Programming Tutorials

CountDownLatch In Java

CountDownLatch in Java

CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.

Working of CountDownLatch: When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread is required to do countdown by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as the count reaches zero, the waiting task starts running.

Example of CountDownLatch

package multithreading.countdownlatchDemo;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        Thread t1 = new Worker(1000, countDownLatch);
        Thread t2 = new Worker(2000, countDownLatch);
        Thread t3 = new Worker(3000, countDownLatch);

        t1.start();
        t2.start();
        t3.start();

        try {
            countDownLatch.await();
            System.out.println("Main thread start executing...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}


class Worker extends Thread {
    private int delay;
    private CountDownLatch countDownLatch;

    public Worker(int delay, CountDownLatch latch) {
        this.delay = delay;
        this.countDownLatch = latch;
    }

    @Override
    public void run() {
        super.run();
        try {
            Thread.sleep(this.delay);
            this.countDownLatch.countDown();
            System.out.println(Thread.currentThread().getName() + " is running!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output

Thread-0 is running!
Thread-1 is running!
Thread-2 is running!
Main thread start executing...

Facts about CountDownLatch:

  1. Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually a number of invited parties (threads) for an event.

  2. The thread, which is dependent on other threads to start processing, waits on until every other thread has called countdown. All threads, which are waiting on await() proceed together once countdown reaches to zero.

  3. countDown() method decrements the count and await() method blocks until count == 0

Leave a Reply

Close Menu