×

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread are finished.

We give the constructor the count to start it out with. The await methods stall when the countDown() method is used until the count hits zero, at which point any waiting threads are freed and any additional await method calls instantly return. The thread countdown() is not required to wait until the count is 0 before continuing by CountDownLatch. It holds up progress until all threads have passed in order to prevent any from continuing.

Depending on the count value, the CountDownLatch is utilised for a number of reasons, including:

  1. The CountDownlatch will function as a straightforward on/off latch or gate if initialised with count value 1.
  2. When the CountDownLatch is initialised with the parameter N, it will be utilized to force one thread to wait until N other threads have finished performing some action or until an action has been performed N times.

CountDownLatch constructor

A constructor with parameters is offered by CountDownLatch. For the count, it allows an integer number. The CountDownLatch is built, and the specified count value is used to initialise it.

Note: Whenever the result of count is negative, constructor raises an Illegal Argument Exception.

Its syntax is

public CountDownLatch( int count ) 

The parameters are

The count parameter determines how many instances countdown() must be used before the thread may go past await().

Approaches to CountDownLatch

We may control concurrency using a number of the methods provided by the CountDownLatch class. The CountDownLatch class additionally offers Java.lang methods. Because the CountDownLatch class inherits from it, it is an object class.

Following is a list of the class java.lang.methods: Object's:

  • The clone
  • Equals to
  • To finalize
  • getClass
  • hashCode
  • notify
  • notifyAll
  • wait

These are the techniques that the CountDownLatch offers:

1. await(): The current thread will wait using the await() function until none of the following has been completed:

  1. The latch has counted down to the zero
  2. Interruption of the thread is not yet done.

When the current count value is set to 0, the await() function returns right away.

Whenever the current count is neither 0 nor a negative number and the current thread is idle until one of the following events occurs, the await() function disables that existing task for thread scheduling reasons.

  • Due to the count's invocations, the level of the count falls to zero.
  • Down() Another thread has interrupted the current thread.

Syntax is:

The syntax for the await() function is as follows:

public void await() 

Both the value it accepts and the value it returns are zero.

Throws

When the waiting thread is interrupted, the await() function throws the interruptedException exception.

2. await(): Another application of the await() function, it makes the running thread await till the preceding is not accomplished

  • The latch has reached zero and is closed.
  • The allotted waiting period has passed.
  • The thread is cut off.

If the current count value is set to zero, the await() function instantly returns the value true.

Whenever the current total would be neither zero nor negative, the await() function disabled the active thread for scheduling reasons, and the active thread remained idle until any of the following events occurred:

  • Since the count is used so often, its value eventually drops to zero.
  • There has been enough waiting time.
  • Some other thread is interfering with the one that is now running.

Its synatax is:

public boolean await( lasting timeout, TimeUnit unit)

Let's use the CountDownLatch as an example to better understand how it functions and what Java can do to implement it.

Let the file name be CountDownLatchDemo.java

// add the necessary classes and packages
package ptron.GoogleJava;
import java.util.concur.CountDownLatch; 
// To comprehend how we might utilise it, we construct the CountDownLatchExample class.
public class CountDownLatchDemo  
{  
    // the main() method will get started  
    public static void main(String args[]) throws InterruptedException  // latch is capable of tossing InterruptedException
    {  
        // We now build a job that will delay execution for 3 threads.
        CountDownLatch CODOLatch = new CountDownLatch(3);  
        // We now generate all three threads and launch them.
        Workers t1 = new Workers(4000, CODOLatch, "Workers T-4");  
        Workers t2 = new Workers(3000, CODOLatch, "Workers T-3");  
        Workers t3 = new Workers(2000, CODOLatch, "Workers T-2");            
        // launch all 3 threads
        t1.start();  
        t2.start();  
        t3.start();    
        // Use the await() function to wait for 3 threads while the main job is running.
        CODOLatch.await();  
        // The primary thread has begun.
        System.out.println("Thread " + Thread.currentThread().getName() + " has completed");  
    }  
}   
// For representing threads and those on which the main thread will wait, build the Workers Thread class. 
class Worker extends thread  
{  
    // declare the variables delay and CODOLatch.
    private int delay;  
    private CountDownLatch CODOLatch;  
      
    // constructor with parameters to set the variables' values
    public Worker(int delay, CountDownLatch CODOLatch, String name)  
    {  
        super(name);  
        this.delay = delay;  
        this.CODOLatch = CODOLatch;  
    }  
      
    // To run a thread, override the run() function of the Thread class.
    @Override  
    public void run()  
    {  
        // Utilize a try block to run a thread and obtain the count value.
        try  
        {  
            Thread.sleep(delay);  
            CODOLatch.countDown();    // utilise the CountDownLatch's countDown() function.
            System.out.println(Thread.currentThread().getName() + " has completed");  
        }  
        // To handle InterruptedException, utilise a catch block
        catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        }  
    }  
}

Output:

Workers T-3 has completed
Workers T-2 has completed
Workers T-1 has completed

Related Topics

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.