×

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

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Awesome explanation of Strings 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.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 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 Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.