Java Concurrency Model - Part II - CountDownLatch

Note: Get the source code from

In this post i have tried to show an example using CountDownlatch, a synchronizer in Java concurrency framework.

Class CountDownLatchTest

package com.somitsolutions.training.java.ExperimentationWithCountdownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CountDownLatchTest {

    public static void main(String args[]) {
        final CountDownLatch latch = new CountDownLatch(3);
        Thread service1 = new Thread(new Service("Service1", 1000, latch));
        Thread service2 = new Thread(new Service("Service2", 1000, latch));
        Thread service3 = new Thread(new Service("Service3", 1000, latch));

        service1.start();
        service2.start();
        service3.start();

        // Application should not start processing any thread until all services are up
        // and ready to do their job.
        // CountDownLatch is an ideal choice here. The main thread will start with count 3
        // and wait until the count reaches zero. Each thread, once up and ready, will do
        // a countdown. This will ensure that the main thread does not start processing
        // until all services are up.

        // Count is 3 since we have 3 Threads (Services)
        try {
            latch.await(); // Main thread is waiting on CountDownLatch to finish
            System.out.println("All services are up, Application is starting now");
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

class Service implements Runnable {
    private final String name;
    private final int timeToStart;
    private final CountDownLatch latch;

    public Service(String name, int timeToStart, CountDownLatch latch) {
        this.name = name;
        this.timeToStart = timeToStart;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(timeToStart);
        } catch (InterruptedException ex) {
            Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(name + " is Up");
        latch.countDown(); // Reduce count of CountDownLatch by 1
    }
}
0
Subscribe to my newsletter

Read articles from Somenath Mukhopadhyay directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Somenath Mukhopadhyay
Somenath Mukhopadhyay

To win is no more than this... To rise each time you fall...