As each Java document describes, Countdownlatch is a synchronization tool class that allows one or more threads to wait until the other thread's operations have been executed. In Java concurrency, the concept of countdownlatch is a common face test, so make sure you understand it well. In this article, I'll cover the following points related to Countdownlatch in Java concurrent programming: What is Countdownlatch?
Countdownlatch was introduced in java1.5, and the concurrent tool classes introduced with it were cyclicbarrier, Semaphore, Concurrenthashmap, and Blockingqueue, They all exist under the Java.util.concurrent package. Countdownlatch This class enables a thread to wait for another thread to complete its own work before executing. For example, the main thread of the application wants to execute after all the framework services have been started by the threads responsible for starting the framework service.
The Countdownlatch is implemented by a counter that has the initial value of the number of threads. Each time a thread completes its own task, the value of the counter is reduced by 1. When the counter value reaches 0 o'clock, it means that all threads have completed the task, and then the thread waiting on the latch can resume the task.
The pseudo code for Countdownlatch is as follows:
Main thread start
//create countdownlatch for n threads
//create and start n threads
//main thread wait on l Atch
//n Threads completes there tasks are returns
thread//main resume
How Countdownlatch works
constructor defined in the Countdownlatch.java class:
Constructs a countdownlatch initialized with the given count.
public void Countdownlatch (int count) {...}
The Count value (count) in the constructor is actually the number of threads that need to wait for the lock. This value can only be set once, and Countdownlatch does not provide any mechanism to reset the count value.
The first interaction with Countdownlatch is the main thread waiting for other threads. The main thread must call the Countdownlatch.await () method immediately after starting another thread. The operation of the main thread blocks this method until the other threads complete their respective tasks.
Other n threads must refer to the locked object because they need to notify the Countdownlatch object that they have completed their respective tasks. This notification mechanism is done through the Countdownlatch.countdown () method, and each time this method is invoked, the count value initialized in the constructor is reduced by 1. So when n threads call this method, the value of Count equals 0, and then the main thread can resume its task through the await () method. usage scenarios in real-time systems
Let's try to list what usage scenarios are countdownlatch in Java real-time systems. What I have listed is all I can think of. If you have other possible ways to use it, please list it in your message, which will help you.
(1) Achieve maximum parallelism: Sometimes we want to start multiple threads at the same time to achieve the greatest degree of parallelism. For example, we want to test a single instance class. If we create a countdownlatch with an initial count of 1 and have all the threads wait on this lock, then we can easily complete the test. We only need to call the countdown () method once to get all the waiting threads back to execution at the same time.
(2) Wait for n threads to complete their tasks before starting execution: for example, the application startup class ensures that all n external systems are started and run before the user request is processed.
(3) Deadlock detection: A very convenient use scenario is that you can use N threads to access shared resources, the number of threads in each test phase is different, and try to produce a deadlock. Countdownlatch Use examples
In this example, I simulate an application startup class that starts with n thread classes that check the external system and notify the latch, and the startup class waits on the latch. Once all external services have been validated and checked, the startup class resumes execution.
Basehealthchecker.java: This class is a runnable, responsible for all specific external service health checks. It removes duplicate code and locked central control Code.
Public abstract class Basehealthchecker implements Runnable {private Countdownlatch _latch;
Private String _servicename;
Private Boolean _serviceup; The thread can countdown () the latch public basehealt the "Get latch object" constructor so and after completing the task
Hchecker (String serviceName, Countdownlatch latch) {super ();
This._latch = latch;
This._servicename = ServiceName;
This._serviceup = false;
@Override public void Run () {try {verifyservice ();
_serviceup = true;
catch (Throwable t) {t.printstacktrace (system.err);
_serviceup = false;
finally {if (_latch!= null) {_latch.countdown ();
}} public String Getservicename () {return _servicename;
public Boolean isserviceup () {return _serviceup; }//this Methos needs to is implemented by all specific service checker public abstract void Verifyservice (); }
Networkhealthchecker.java: This class inherits the Basehealthchecker and implements the Verifyservice () method. Databasehealthchecker.java and Cachehealthchecker.java are the same as Networkhealthchecker.java except for the service name and hibernation time.
public class Networkhealthchecker extends Basehealthchecker
{public
networkhealthchecker (countdownlatch Latch) {
super ("Network Service", latch);
}
@Override public
void Verifyservice ()
{
System.out.println ("Checking" + this.getservicename ());
Try
{
thread.sleep (7000);
}
catch (interruptedexception e)
{
e.printstacktrace ();
}
System.out.println (This.getservicename () + "is");
}
Applicationstartuputil.java: This class is a Master startup class that is responsible for initializing the latch and then waiting until all the services have been detected.
public class Applicationstartuputil {//list of service checkers private static list<basehealthchecker> _ser
vices;
This latch'll is used to wait on the private static Countdownlatch _latch; Private Applicationstartuputil () {} private final static applicationstartuputil INSTANCE = new Applicationst
Artuputil ();
public static Applicationstartuputil getinstance () {return INSTANCE; public static Boolean checkexternalservices () throws Exception {//initialize-latch with number of
Service Checkers _latch = new Countdownlatch (3);
All add Checker in lists _services = new arraylist<basehealthchecker> ();
_services.add (New Networkhealthchecker (_latch));
_services.add (New Cachehealthchecker (_latch));
_services.add (New Databasehealthchecker (_latch)); Start Service checkers using executor framework Executor executor = Executors.newfixedthreAdpool (_services.size ());
For (final Basehealthchecker V: _services) {executor.execute (v);
}//now wait till all services are checked _latch.await (); Services are file and now proceed startup for (final Basehealthchecker V: _services) {if (!
V.isserviceup ()) {return false;
} return true; }
}
Now you can write the test code to detect the blocking function.
public class Main {public
static void Main (string[] args)
{
Boolean result = false;
try {result
= Applicationstartuputil.checkexternalservices ();
} catch (Exception e) {
e.printstacktrace ( );
}
System.out.println ("External Services validation completed!! Result is:: "+ result);
}
Output in console:
Checking Network Service
Checking Cache service
Checking Database service
The Database Service is the up
Cache service are up
Network service are up
External services validation completed!! Result is:: True
Common face questions
You can prepare the following Countdownlatch related questions for your next interview: Explain the Countdownlatch concept? What's the difference between Countdownlatch and cyclicbarrier? Give some examples of countdownlatch use? The main method in the Countdownlatch class? Notes
Original link: http://howtodoinjava.com/core-java/multi-threading/ when-to-use-countdownlatch-java-concurrency-example-tutorial/
Translation Links: http://www.importnew.com/15731.html