×

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

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.