×

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 Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 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.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 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 Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Three Partition Problems 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...

8 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.