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:
- The CountDownlatch will function as a straightforward on/off latch or gate if initialised with count value 1.
- 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:
- The latch has counted down to the zero
- 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