In previous articles, we introduced the tools for concurrent programming in Java: BlockingQueue interface, ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, BlockingDeque interface ConcurrentHashMap. This is the ninth article in the series.

CountDownLatch is a thread synchronization aid that allows one or more threads to wait for a set of actions that other threads are performing to complete. The concept of CountDownLatch is very common in Concurrent Java programming and is often asked in interviews, so it’s important to understand it. In this article, I will introduce the following points

  • What is CountDownLatch?
  • How does CountDownLatch work
  • CountDownLatch code example

What is CountDownLatch?

CountDownLatch was introduced with JDK 1.5 in the java.util. Concurrent package along with other concurrent programming tool classes such as CyclicBarrier, Semaphore, ConcurrentHashMap, and BlockingQueue. CountDownLatch enables a Java thread to wait for other threads to complete tasks, such as the main thread of the Application, until the other service threads responsible for starting framework services have started all services.

CountDownLatch initializes a counter with the number of threads that are decremented each time a thread completes execution. When the count is zero, it indicates that all threads have completed execution and the main thread in the waiting state can continue execution.

Here we describe CountDownLatch in pseudocode

  • The main thread starts and initializes CountDownLatch(N) for N threads (assuming N =3)
  • Start n threads
  • The main thread is blocked and waiting
  • Thread 1 completes, CountDownLatch -1 = 2, and the main thread continues to block
  • Thread 3 completes, CountDownLatch -1 = 1, and the main thread continues to block
  • Thread 4 completes, CountDownLatch -1 = 0, and the main thread resumes execution

How does CountDownLatch work

The countDownlatk. Java class defines a constructor. Count is essentially the number of threads. This value can only be set once, and CountDownLatch does not provide a way to reset this number.

CountDownLatch.public CountDownLatch(int count) {... }Copy the code

The main thread using CountDownLatch has to wait for another thread to complete, so the main thread must call countdownlatch.await () as soon as the other thread is started. This method blocks the main thread in the wait state until the other thread completes.

The other N threads must have a reference to the CountDownLatch object because they need to notify the CountDownLatch object that they have completed their task. This notification is done by the method countdownlatch.countdown (), which reduces the initial count set in the constructor by one each time it is called, so that when all N threads have called it, the count reaches zero, The main thread can resume execution without being blocked by the await() method.

So CountDownLatch is especially good for scenarios where you need to wait N threads to complete before starting execution. For example, an application startup class ensures that all N external systems are up and running before processing user requests.

CountDownLatch code example

Suppose that before our main application starts, we need to check that the other four programs are ready. Our main application cannot continue until the other four programs are ready. You can use the following code to do this:

import java.util.concurrent.CountDownLatch; Public class Tester {public static void main(String args[]) {// Set counter counter = 4, CountDownLatch CountDownLatch = new CountDownLatch(4); Thread app1 = new Thread(new Application("App1", countDownLatch)); Thread app2 = new Thread(new Application("App2", countDownLatch)); Thread app3 = new Thread(new Application("App3", countDownLatch)); Thread app4 = new Thread(new Application("App4", countDownLatch)); // Start multithreading to check the availability of the other four programs app1.start(); app2.start(); app3.start(); app4.start(); // The main thread calls await to complete countdownlatch.await (); System.out.println("All applications are up and running."); } catch(InterruptedException e) { System.out.println(e.getMessage()); }}}Copy the code

Child thread program, each thread holds the countDownLatch object. Upon completion of the thread’s normal execution, the countDownLatch. CountDown () method is used to reduce the countDownLatch object’s counter by one.

class Application implements Runnable { private String name; Private CountDownLatch CountDownLatch; public Application(String name, CountDownLatch countDownLatch) { this.name = name; this.countDownLatch = countDownLatch; } public void run() { try { System.out.println(name + " started. "); Thread.sleep(1000); } catch (InterruptedException e) { System.out.println(e.getMessage()); } System.out.println( name + " is Up and running."); Countdownlatch.countdown (); }}Copy the code

The printout of the above program can be used to understand the working principle of CountDownLatch described above:

App2 started.  
App3 started.  
App1 started.  
App4 started.  
App1 is Up and running.
App3 is Up and running.
App4 is Up and running.
App2 is Up and running.
All applications are up and running.
Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series