Recently has been working while learning distributed things, see the basics of building Java middleware, there is a reference to Java Multithreading Concurrency tool classes, such as Reentrantlock, Cyclicbarrier, Countdownlatch ...
Previously in the work has also been useful to these practical tools, but the understanding is not particularly deep, take this opportunity to play a card, good memory than bad blog, hahaha ...
- Countdownlatch Introduction
Countdownlatch as the name implies, Count + down + latch = count + minus + latch (so split is also easy to remember =_=) can understand this thing is a counter, can only reduce the addition, while it also has a latch function, when the counter is not 0 o'clock, the latch is locked; When the number was reduced to 0 o'clock, the latch opened.
If you feel confused, you can compare the examinee examination to hand in, the examinee handed a paper, the counter is reduced one. The Examiner (one or more) will not be able to leave the examination room until the examinee has handed in the test paper (counter 0). As to whether the examinee finishes the examination paper, the Proctor teacher is not concerned. As long as they have handed in the test paper, he can do the next work.
- Countdownlatch Practical Scenarios
Now that you know its definition, when do you use it? The scenario I can think of is:
With Task A and task B, task B must be done after task A is complete. Task A can also be divided into n parts, and the tasks between the N parts do not affect each other. In order to speed up the progress of the task, the N part of the task is divided into different threads, when a task is completed, and then notify the thread of the B task to complete the task, as to the completion of the B task of the thread, can be one, or can be multiple.
:
- Countdownlatch Implementation principle
Next, with the author to pick a grilled countdownlatch source code, it is how to achieve this function. (source version JDK1.8)
Public classCountdownlatch {//Inner class inherits Aqs class Private Static Final classSyncextendsAbstractqueuedsynchronizer {Private Static Final LongSerialversionuid = 4982264981922014374L; Sync (intcount) {setState (count); } intGetCount () {returngetState (); } protected intTryacquireshared (intacquires) { return(getState () = = 0)? 1:-1; } protected BooleanTryreleaseshared (intreleases) { for (;;) { intc =getState (); if(c = = 0) return false; intNEXTC = c-1; if(Compareandsetstate (c, NEXTC))returnNEXTC = = 0; } } } //instance object of the Aqs child class Private FinalSync Sync; //a parametric constructor PublicCountdownlatch (intcount) { if(Count < 0)Throw NewIllegalArgumentException ("Count < 0"); This. sync =NewSync (count); } //wait Public voidAwait ()throwsinterruptedexception {sync.acquiresharedinterruptibly (1); } //Timeout Wait Public BooleanAwaitLongTimeout, timeunit unit)throwsinterruptedexception {returnSync.tryacquiresharednanos (1, Unit.tonanos (timeout)); } //count minus 1 Public voidcountdown () {sync.releaseshared (1); } //Get counter Current count Public LongGetCount () {returnSync.getcount (); } //that's not a lot of toast . PublicString toString () {return Super. toString () + "[Count =" + sync.getcount () + "]"; }}
Readers familiar with Reentrantlock should know this structure, it is also used this structure to complete the function, but reentrantlock in the internal class sync, it also divided the Nonfairsync (non-fair lock) and Fairsync (Fair lock) These two classes inherit the parent class of sync. The advantage of this structure is that we don't have to care about the specifics of the implementation of the Abstractqueuedsynchronizer, just implement the method it wants us to implement (for example: tryacquireshared tryreleaseshared) to generate our specific concurrency business tool classes.
Pull away. Ha, Next I will be divided into two lines to analyze Countdownlatch, one is countdownlatch.await () blocking the current thread, and the second is Countdownlatch.countdown () the current thread to reduce the counter one
First, countdownlatch.await ()
Imagine:
Question: What are the methods you can think of to achieve this function?
Answer: First you might use the thread's join () to let the current thread wait for the join thread to finish executing. The principle is that the join thread is constantly checked for survival, and the current thread waits forever if the join thread survives.
Second you may use inter-threading wait/notify, enter the synchronized synchronization block or method, check that the counter value is not 0, and then call Object.wait (), until a value of 0 calls the Notifyall () wake-up waiting thread.
Analysis: Method One if only two or three threads are OK, if the number is too much, it must write how many join Ah ...
Method two large synchronized synchronous block, there may be false wake ...
Conclusion: The above mentioned methods are more or less in such a disadvantage, then we guess the idea of solving these shortcomings
First, we may need a volatile variable to sense the value of the counter in real time, and once the counter value is 0, the thread that blocks on that condition is awakened
Second, because volatile has only real-time transparency of data, it does not guarantee the sequential execution of threads, so we may need a synchronization queue to place these blocking queues, and when the counter value is 0 o'clock, wake the thread from the queue
Let's start with our verification:
Public Countdownlatch (int count) { ifthrownew illegalargumentexception ( "Count < 0"); This New Sync (count);} Sync (int count) { setState (count);}
The construction method passed in an int variable, and we followed it to find that the int variable is the state in Aqs, and the type is volatile, which is used to represent the counter value. And this proves our conjecture. Note: The count value needs to be greater than or equal to 0
Public void throws interruptedexception { sync.acquiresharedinterruptibly (1);}
When we call the await () method, the Acquiresharedinterruptibly method of the instance of sync is called by default, and the parameter is 1, it is important to note that this method declares a interruptedexception exception, Indicates that the thread that called the method supports the interrupt operation.
Public Final void acquiresharedinterruptibly (int arg) throws interruptedexception { if (thread.interrupted ()) Throw New interruptedexception (); if (Tryacquireshared (ARG) < 0) doacquiresharedinterruptibly (ARG);}
We follow the source discovery, acquiresharedinterruptibly This method is the sync inherited Aqs, this method is called by the response thread interrupt, so in the first two rows check whether the thread is interrupted. The Tryacquireshared () method is then called to determine the return value, depending on the size of the value to determine whether to execute doacquiresharedinterruptibly ().
int Tryacquireshared (int Arg) { throw new Unsupportedoperationexception ();} Methods in sync protected int Tryacquireshared (int acquires) { return (getState () = = 0)? 1: -1 protected final int GetState () { return state;//state is volatile}
We see that aqs this method to the subclass to achieve, in the sub-class sync tryacquireshared It only verifies that the value of the counter is 0, if 0 is returned 1, and vice versa-1, according to the above can be seen, The integer does not execute doacquiresharedinterruptibly (), the thread ends the method, and continues to execute its own code.
Private voidDoacquiresharedinterruptibly (intArg)throwsinterruptedexception {FinalNode node =Addwaiter (node.shared);//Add nodes to the synchronization queueBooleanFailed =true; Try { for (;;) {//A dead loop jumps out of the loop only the following two waysFinalNode p =node.predecessor ();///When the previous node of the front threadif(p = =head) {//If it is the first nodeintR =tryacquireshared (ARG);//Is this déjà vu seen above?if(r >= 0{setheadandpropagate (node, r);//process subsequent nodes P.next=NULL;//help GC This can be borrowed fromFailed =false; return;//The Count value is 0 and the head node jumps out of the loop}} if(Shouldparkafterfailedacquire (p, node) &&parkandcheckinterrupt ())Throw Newinterruptedexception ();//Response Interrupt Bounce Loop}} finally { if(failed) cancelacquire (node); Remove the synchronization queue node if it is interrupted}}
Then we look at doacquiresharedinterruptibly this method, because the counter value does not 0 need to block the thread, so when the method is entered, the thread is wrapped into a node and added to the tail of the synchronization queue (how to add the source code to show later), We see that this method exits the path straight to two, one is return, and the other is the throw interruptedexception. Pay attention to the final finally treatment.
The return exit method has two conditions, first the count value is 0, and then must be the first node of the synchronization node.
Throw Interruptedexception is a response interrupt operation, the thread during blocking, if you do not want to wait, you can hit the thread to keep it running behind the task (note exception handling)
Then we look at the source of the added node:
Privatenode Addwaiter (node mode) {node node=NewNode (Thread.CurrentThread (), mode);//Wrapper nodeNode pred =tail;//Synchronization Queue tail nodeif(Pred! =NULL{//sync queue has tail nodes add our nodes to the queue after the CAs method Node.prev=pred; if(Compareandsettail (pred, node)) {//Add tail node as CAs atom Pred.next=node; returnnode;//exit the method}} Enq (node);//Two cases execute this code 1. The tail node of the queue is null 2. The tail node of the queue is not NULL, but we failed to add the tail nodereturnnode;}PrivateNode Enq (Finalnode node) { for (;;) {//is also a dead loop Node t=tail; if(T = =NULL) {//must initialize if(Compareandsethead (NewNode ())) CAS form Add Head node note is the head node tail=Head; } Else{Node.prev=T; if(Compareandsettail (t, node)) {//cas form add tail node T.next=node; returnt;//End This method's only exit add tail node success}} }}
At this point, countdownlatch.await () blocks the basic functionality of the current thread has been combed out, countdownlatch.countdown () counter minus a function and Countdownlatch example and its advantages and disadvantages will remain in the next part of the comb.
Then, the Compareandsethead () and Compareandsettail (), which are confined to more space, are not listed in detail and want readers to see the API themselves.
Finally, due to the author's limited level, inevitably there are shortcomings, there is no place, please do not hesitate to advise. Thank you!
Java Countdownlatch parsing (top)