Understanding Java CountDownLatch

Understanding Java CountDownLatch



A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset.

This method causes the thread to sleep until the operations are completed. Whenever any of these operations are completed, using the countDown() method it decrements the internal counter of the CountDownLatch class. When the counter value becomes zero, the class wakes up all the threads that were sleeping in the await() method.
Consider you are having multiple services that you want up and running in your project. But the requirement is the main service should be started only after some other services like database service, cache service and security service have started. This is where we will use a countDownLatch.
Using countDownLatch we will make the main service wait till the other required services have started.
The following are the main methods of countdownlatch-
Method Description
countDownLatch(int count) Creates an instance of CountDownLatch with the number of times the countDown() method must be called before the threads waiting with await()can continue execution
void countDown() Reduces the number of counts by one in this CountDownLatch object. If the count reaches zero, all the (a)waiting threads are released. If the current count is already zero, nothing happens
long getCount() Returns the pending counts in this CountDownLatch object
void await() If the current count in CountDownLatch object is zero, it immediately returns; otherwise, the thread blocks until the countdown reaches zero. Can throw an InterruptedException
package com.javastructures;

import java.util.concurrent.CountDownLatch;

public class Service implements Runnable {
	private String serviceName;
	private int timeToBegin;
	private CountDownLatch countDownLatch;
	
	public Service(String serviceName, int timeToBegin, CountDownLatch countDownLatch) {
		super();
		this.serviceName = serviceName;
		this.timeToBegin = timeToBegin;
		this.countDownLatch = countDownLatch;
	}
	
	
	public void run() {
			try {
				Thread.sleep(timeToBegin);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("The service - " + serviceName + " is up and running");
			countDownLatch.countDown();
		
	}

}
	
package com.javastructures;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

	public static void main(String args[]) {
		CountDownLatch serviceCountdownLatch = new CountDownLatch(3);
		Thread dataBaseService = new Thread(new Service("databaseService", 1000, serviceCountdownLatch));
		Thread cacheService = new Thread(new Service("cacheService", 1000, serviceCountdownLatch));
		Thread securityService = new Thread(new Service("securityService", 1000, serviceCountdownLatch));

		dataBaseService.start();
		cacheService.start();
		securityService.start();

		try {
			serviceCountdownLatch.await();
			System.out.println("All 3 services are up and running now we can start the main service");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
	
Run the program as a Java Application - Java Program for countdownlatch