Java_ Latching _countdownlatch Applications

Source: Internet
Author: User

Java_ Latching _countdownlatch Applications


latching is a synchronization tool class that can delay the progress of a thread until it reaches the terminating state. latching acts as a door: the door is closed until it reaches the end state, and no thread can pass, and when the end state is reached, the door opens and allows all threads to pass. When the latch reaches the end state, it will not change state, so the keeper remains open forever. latching can be used to determine that certain activities are not resumed until other activities have been completed, such as:

    • Make sure that a calculation does not continue until all of the resources it needs are initialized. a two-yuan lockout (including two states) can be used to indicate that "resource R has been initialized" and that all operations requiring r must wait on this lockout

    • Make sure that a service starts only after all other services it relies on are already started. each service has a related two-dollar lockout. When the service S is started, it will first wait on the lockout of the other services that s relies on, and will release the lockout s when all dependent services are started, so that other services dependent on S can continue to execute.

    • wait until all the participants in an operation are ready to continue execution. in this case, when all players are ready, the lockout will reach the end state.


Countdownlatch is a flexible latching implementation that can be used in the above scenario, and he can make one or more threads wait for a set of time to occur. The latching state includes a counter that is initialized to a positive number, which indicates how many events need to wait. The countdown method decrements the counter, indicating that an event has occurred, while the await method waits for the counter to reach 0, which means that all events that need to wait have already occurred. If the value of the counter is nonzero, then the await is blocked until the counter is zero, or the waiting thread is interrupted, or the wait times out.


Await () method increment counter

Causes the current thread to wait until the latch have counted down to zero

/** * causes the current thread to wait until the latch  has counted down to * zero, unless the thread is {@ linkplain thread#interrupt interrupted}. * * <p>if the current  count is zero then this method returns immediately. * * < p>if the current count is greater than zero then the  current * thread becomes disabled for thread scheduling purposes  and lies * dormant until one of two things happen: *  <ul> * <li>The count reaches zero due to invocations  of the * {@link   #countDown} method; or * <li>some other  thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul>  * * <p>if the current thread: * <ul> * <li >has its interrupted status set on entry to this method;  or * <li>is {@linkplain  thread#interrupt interrupted} while waiting,  * </ul> * then {@link  interruptedexception} is thrown and  the current thread ' s * interrupted status is cleared. * *   @throws  interruptedexception if the current thread is interrupted  *         while waiting */public void  Await ()  throws interruptedexception {    sync.acquiresharedinterruptibly (1) ;}


Countdown () Method Decrement counter

Decrements the count of the latch, releasing all waiting threads if the count reaches zero

/** * Decrements the Count of the latch, releasing all waiting threads if * The count reaches zero. * * <p>if The current count is greater than zero and it is decremented. * If The new count is zero and all waiting threads be re-enabled for * thread scheduling purposes. * * <p>if the current count equals zero and nothing happens. */public void Countdown () {sync.releaseshared (1);}


Java Concurrency Programming Practical example

In the following example, it uses two latching, representing the starting gate, and the end gate, respectively.

The initial value of the

start gate counter is 1, and the initial value of the end gate counter is the number of worker threads. The first thing each worker has to do is to wait on the startup door to ensure that all the threads are ready before they start executing. The last thing each thread has to do is subtract one from the countdown method that calls the end gate, which allows the main thread to wait efficiently until all the worker threads are done, so you can count the time spent:

package com.lyx;import java.util.concurrent.countdownlatch;public class testharness { Public static void main (String[] args)  throws interruptedexception {//  todo auto-generated method stubrunnable task = new runnable ()  { Public void run ()  {system.out.println ("Hello latch .....");}; System.out.println (TIMETASHS (100, task));} PUBLIC&NBSP;STATIC&NBSP;LONG&NBSP;TIMETASHS (Int nthreads, final runnable task) throws  Interruptedexception {final countdownlatch startgate = new countdownlatch (1); Final countdownlatch endgate = new countdownlatch (nthreads);for  (int i  = 0; i < nthreads; i++)  {thread t = new thread ()  {@Overridepublic  void run ()  {try {startgate.await (); Try {task.run ();}  finallY {endgate.countdown ();}}  catch  (interruptedexception e)  {// todo: handle exception}}};t.start ();} Long start = system.nanotime (); Startgate.countdown (); endgate.await ();long end =  System.nanotime (); return end - start;}}


The following example is from http://lbxc.iteye.com/blog/1717482

Public long runsample (Int n, final runnable runsport)  throws  interruptedexception {    final countdownlatch gun = new  Countdownlatch (1);    final countdownlatch end = new  Countdownlatch (n);        for  (int i = 0; i  < n; i++) {        thread t = new  thread ()  {            public void  run () {                 Try{                gun.await ( );//wait for the shot                 try{        &nbSp;        runsport.run ();                 }finally{                     end.countdown ();                 }                 }catch ( InterruptedException  e) {                     thread.currentthread (). Interrupt ();                 }             }        };         t.start ();     }    long starttime = system.nanotime ();     Gun.countdown ();//Shot     end.await ();    long endtime =  System.nanotime ();     return endtime - starttime;}


====================end====================


Java_ Latching _countdownlatch Applications

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.