Multi-thread programming -- CountDownLatch for asynchronous Synchronization

Source: Internet
Author: User

In daily development, we often encounter this situation: for some asynchronous requests, we need to wait until the request is received before executing the next action. In this case, we need to convert the asynchronous action into a synchronous action.


Java provides a CountDownLatch class to implement this function.


Let's take a look at the official definitions of CountDownLatch:

A synchronization aid that allows one or more threads to wait until a set of operations being stored med in other threads completes.

CountDownLatch is a synchronization assistant that enables one or more threads to wait until a series of actions executed in other threads are completed (these threads are awakened)


How to use it?

See this document:

ACountDownLatchIs initialized with a givenCount.await()Methods block until the current count reaches zero due to invocations of the countDown () method, after which all waiting threads are released and any subsequent invocationsawait()Return immediately.


A useful property ofCountDownLatchIs that it doesn' t require that threads callingcountDownWait for the count to reach zero before proceeding, it simply prevents any thread from proceeding pastawait()Until all threads cocould pass.

There will be deviations in this sentence.


Detailed use cases:

class Driver { // ...      void main() throws InterruptedException {      CountDownLatch startSignal = new CountDownLatch(1);      CountDownLatch doneSignal = new CountDownLatch(N);            for (int i = 0; i < N; ++i) // create and start threads        new Thread(new Worker(startSignal, doneSignal)).start();            doSomethingElse();            // don't let run yet      startSignal.countDown();      // let all threads proceed      doSomethingElse();      doneSignal.await();           // wait for all to finish  }     class Worker implements Runnable {    private final CountDownLatch startSignal;    private final CountDownLatch doneSignal;       Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {      this.startSignal = startSignal;      this.doneSignal = doneSignal;    }    public void run() {      try {        startSignal.await();        doWork();        doneSignal.countDown();      } catch (InterruptedException ex) {} // return;    }         void doWork() { ... }    }}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.