Handling concurrent threads using Countdownlatch and Cyclicbarrier

Source: Internet
Author: User

gossip does not say, first look at a section of code:
{Ivaluecallback remotecallback = new Ivaluecallback.stub () {<strong><span style= "color: #ff0000;" > (B) </span></strong> public void Onreceivevalue (final Bundle value) throws RemoteException { Synchronized (syncobject) {mreturnvalue = Arg.result;syncobject.notify ();//Run complete, notify notification code continues}}};boolean bsuccess = False;synchronized (syncobject) {<strong><span style= "color: #ff0000;" > (A) </span></strong>sendrequest (Commandconstant.command_navigation_item_exist, ARG, Remotecallback); try {syncobject.wait (5000);//wait for the callback part to run complete} catch (Interruptedexception e) {e.printstacktrace ();}} return mreturnvalue;}


To analyze the effect of this code: after running (A) block, let the thread wait for the (B) block to return the result and notify the end of the wait-and-return result value. Aside from readability. This processing is able to complete the "Sync request". But . Take a look at some possible problems-Suppose there are two callback functions in the Ivaluecallback, and the return result depends on the value returned by the two callbacks, how does the sync lock add? How notify?
Thought for a minute. Still a little headache? Okay, the following two characters CountdownlatchAnd CyclicbarrierOut.

(never heard of Java these two classes please raise your hand!) I'll give you a toast. )
First introduce Countdownlatch This class:A synchronization aid that allows one or more threads to wait until A s Et of operations being performed in other threads completes.

A is CountDownLatch initialized with a given count. awaitthe methods block until the current count reaches zero due countDown() to invocations of the method, after which all waiting Threads is released and any subsequent invocations of await return immediately. This is a one-shot phenomenon – the count cannot be reset.

That is to say: can think of it as a counter, just this counter operation is atomic operation, at the same time can only have a thread to operate this counter, that is, at the same time can only have a thread to reduce the value of this counter ( countDown()method).

You can set an initial number as the count value to the Countdownlatch object. Any call to the await () method on this object will clog until the count of the counter is reduced to 0 by the other thread.

The above code changes are:

{Countdownlatch CDL = new Countdownlatch (2),//2 counter ivaluecallback remotecallback = new Ivaluecallback.stub () {(B) publi c void Onreceivevaluea (final Bundle value) throws RemoteException {mreturnvalue = Arg.result && mreturnvalue; CDL. Countdown (); Lower one count}public void Onreceivevalueb (final Bundle value) throws RemoteException {Mreturnvalue = arg.result&& mRe Turnvalue; Cdl.countdown (); Lower one count}}};boolean bsuccess = false; (A) SendRequest (Commandconstant.command_navigation_item_exist, ARG, Remotecallback), try {cdl.await ()//etc counter Clear 0 returns the result} catch (Interruptedexception e) {e.printstacktrace ();} return mreturnvalue;}


can see:The callback function is added to two, but the Countdownlatch class easily overcomes this problem and avoids explicit use of synchronous locks.

And this kind of really powerful place is. It can be used flexibly for parameter passing, to write many other code that solves the synchronization problem. And bring a more clear idea than the explicit synchronization lock.

Understand this class, Cyclicbarrier also easy understand, Cyclicbarrier class uses a similar method, but it is used to add to a fixed value when an action is triggered.

The following is an example of LOL entering the league of Legends game. Need A) read progress bar 2) 10 people enter after the ability to start the Game 3) all people buy equipment. Then the method of processing synchronization, can simply use this class to write a demo.

Import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;public class LOLGame {            public static void Main (string[] args) {cyclicbarrier cyclicbarrier = new Cyclicbarrier (Ten, New Runnable () { @Override public void Run () {System.out.println ("Welcome to Summoner Canyon!      ");          }     });     for (int i = 0; i < i++) {new Thread (new Player (I, Cyclicbarrier)). Start ();    }}}class Player implements Runnable {private Cyclicbarrier cyclicbarrier;        private int id;     public Player (int id, cyclicbarrier cyclicbarrier) {this.cyclicbarrier = Cyclicbarrier;    This.id = ID;      } @Override public void Run () {try {System.out.println ("player" + ID + "Reading progress bar ...");      Cyclicbarrier.await ();     System.out.println ("player" + ID + "Purchase equipment ...");     } catch (Interruptedexception e) {e.printstacktrace ();     } catch (Brokenbarrierexception e) {e.printstacktrace (); }    }   }


As forCountdownlatch 's demo will no longer write, we can extrapolate, Internet search information. The solutions to many problems are very subtle. There is also a more subtle example in the official documentationhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html The final summary:1) These two classes were introduced in Java5.0. 2) Countdownlatch is used for reverse counting and cyclicbarrier is used for forward counting, both of which notify the await () section to continue running after the count is complete.

3) detected after rough. The performance of both tools should be higher than using synchronous locks explicitly, but I share this not just for the purpose of transforming the code.

Aside from performance, I personally think that the biggest significance of these two classes is that they provide a way to solve the problem of concurrent threading with atomic counters, and the synchronization problem of multiple threads becomes very clear and abstract.

Compared to an obscure sync lock, the implementation of the counter will be easier to abstract the multithreading problem, focus on the rigor of detailed logic, rather than devote to the potential deadlock and performance consumption headaches.


Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Handling concurrent threads using Countdownlatch and Cyclicbarrier

Related Article

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.