CountDownLatch in Java


For a concurrent execution, CountDownLatch in Java is an important class that ensures one or more threads are in the queue for other threads to complete their set of operations.

To better understand CountDownLatch in Java, in this article, you will learn the working of CountDownLatch with an example and methods of CountDownLatch.

CountDownLatch in Java and its Working Process

Based on the count value, the CountDownLatch is used for several purposes, which are as follows −

  • When we begin the CountDownlatch with count value 1, it will simply work as an on/off latch or gate.

  • On the other hand, when we begin the CountDownLatch with count value N, it causes one thread to wait until N threads complete some action or some action has been completed N times.

Here’s How CountDownLatch in Java works

During the creation of CountDownLatch objects, we should define the number of threads it must wait for. Once it is specified, all such threads are required to do a count down by calling CountDownLatch.countDown(). Upon reaching zero, tasks that are in the queue start running.

Example

Here’s a Java program illustrating CountdownLatch in Java −

import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo{ public static void main(String args[]) throws InterruptedException{ // Lets create a task that needs to wait for four threads before it begins CountDownLatch latch = new CountDownLatch(4); // Let's create four employee threads and begin them. Employee first = new Employee(1000, latch,"EMPLOYEE-1"); Employee second = new Employee(2000, latch,"EMPLOYEE-2"); Employee third = new Employee(3000, latch,"EMPLOYEE-3"); Employee fourth = new Employee(4000, latch,"EMPLOYEE-4"); first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() +" has finished"); } } // A class to represent threads for which the main thread waits. class Employee extends Thread{ private int delay; private CountDownLatch latch; public Employee(int delay, CountDownLatch latch,String name){ super(name); this.delay = delay; this.latch = latch; } @Override public void run(){ try{ Thread.sleep(delay); latch.countDown(); System.out.println(Thread.currentThread().getName()+ " finished"); } catch (InterruptedException e){ e.printStackTrace(); } } }

Output

EMPLOYEE-1 finished
EMPLOYEE-2 finished
EMPLOYEE-3 finished
EMPLOYEE-4 finished
main has finished

From the above program, we can understand that it begins with the count, which we pass to the constructor. Whenever the countDown() method is invoked, the await methods stop up to a point where the count reaches 0. After this point, all waiting threads are released, and any subsequent calls to await are returned immediately

Understanding Constructor of CountDownLatch

The constructor of CountDownLatch is parameterized, and it only accepts an integer value for the count. It constructs the CountDownLatch and begins it with the given count value.

Note− Whenever the value of the count is negative, the constructor throws an IllegalArgumentException

Syntax

public CountDownLatch( int count )

Parameters

count -> It means the number of times the countdown() must be called on before the thread can pass through await().

Methods of CountDownLatch

There are multiple methods in CountDownLatch class that we can use for concurrency control. Additionally, inherited by the CountDownLatch class, the CountDownLatch class provides methods of java.lang.Object class.

The methods of the java.lang.Object class is as follows −

  • clone

  • equals

  • finalize

  • getClass

  • hashCode

  • notify

  • notifyAll

  • wait

  • wait

  • wait

The CountDownLatch provides the following methods −

1. await()

The await() method puts the current thread on hold until any one of the following is not done −

  • The latch has counted down to zero.

  • Thread interruption is not done.

The await() method immediately returns if the current count value is set to zero.

As long as the current count is neither zero nor negative, the await() method disables the current thread for scheduling purposes, and the thread remains dormant until one of the following occurs −

  • The count value reaches zero due to the call of the countDown().

  • Another thread interrupts the current thread.

Syntax

Here’s the syntax for the await() method −

public void await()

It does not accept or return any value.

Throws

The await() method throws interruptedException while the current thread is interrupted on waiting.

2. await()

This is another variation of the await() method which makes the current thread wait until one of the following is not done −

  • The latch has counted down to zero.

  • The specified waiting time is finished.

  • The interruption of the thread.

The await() method as soon as returns the value true when the current count value is set to zero.

As long as the current count is neither zero nor negative, the await() method disables the current thread for scheduling purposes, and the thread remains dormant until one of the following occurs −

  • The count value reaches zero because of the invocations of the countDown()

  • The specified waiting time finishes.

  • The interuption of the current thread by some other thread.

Syntax

public boolean await( long timeout, TimeUnit unit)

Parameters used in the syntax

  • timeout− This is a type long parameter which specifies the maximum time to wait.

  • unit− This specifies the time unit of the timeout argument.

3. Returns

When the count reaches zero, it returns true, whereas it returns false when the waiting time is finished before the count reaches zero.

4. Throws

When there is an interruption of the current thread while waiting, the await() method throws interruptedException.

5. Countdown

Another critical method provided by the CountDownLatch class is the countdown() method. It documents all the latch count and releases all the waiting threads when the count reaches zero. It has done the following things −

  • When the current count is larger/greater than zero, the count decrements.

  • When the new count is zero, all waiting threads will be re-enabled for thread scheduling purposes.

  • However, nothing will happen in the case when the current count equals zero.

6. getCount

getCount() is another important method provided by the CoutDownLatch class. This is used to get the count of the latch which we currently use.

Syntax

public long getCount()

It does not accept any parameter whereas it returns the current count of the latch.

7. toString

The last method provided by the CountDownLatch class is the toString()method. It is used to get a string that will determine the latch and its state.

Syntax

public String toString()

8. Overrides

It overrides the toString in class Object.

9. Returns

It returns the string that will determine the latch and its state.

Wrapping up

With this, we have reached the end of the CountDownLatch tutorial. We hope now you’ve learned what countDownLatch is and how it works. We have also presented you with examples and codes to refer to. If you find this article helpful, give us a thumbs up.

Updated on: 13-Oct-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements