Aqs Source Detailed
Source Analysis Dimension: Synchronization queue, exclusive synchronization state acquisition and release, shared synchronization state acquisition and release, and timeout get synchronization state the core data structure and template method of Synchronizer.
Synchronization Queue Introduction
Synchronizer relies on the internal synchronization queue (a FIFO bidirectional queue) to complete the management of the synchronization state, when the current thread gets the synchronization state fails, the Synchronizer will build the current thread and wait state information such as a node and join the synchronization queue, while blocking the current thread, when the synchronization state is released, Wakes the thread in the first node so that it tries to get the synchronization state again.
Nodes in the synchronization queue are used to hold thread references, wait states, and precursor and successor nodes that have failed to get the synchronization state, and the attribute types and names of the nodes are described in the following:
The basic structure of the synchronization queue is as follows:
The Synchronizer contains a reference to two node types, one pointing to the head node and the other pointing to the tail node. When a thread succeeds in acquiring a synchronization state (or lock), other threads will not be able to get to the synchronization state, instead being constructed into a node and joined to the synchronization queue, and the process of joining the queue must be thread-safe, so the Synchronizer provides a method for setting up tail nodes based on CAS: compareAndSetTail(Node expect , Node update) It needs to pass the tail and current nodes that the current thread "thinks", and only if the settings are successful, the current node is formally associated with the previous tail node.
The Synchronizer joins the node to the synchronization queue as shown in procedure 5-2:
The synchronization queue follows the FIFO, the first node is the node that obtains the synchronization state succeeds, the first node's thread releases the synchronization state, the successor node will wake up, and subsequent nodes will set themselves to the head node when the synchronization state succeeds, such as:
Setting the first node is accomplished by obtaining a thread that has a successful synchronization state, because only one thread can successfully get to the synchronization state, so the method of setting up the head node does not need to use CAs to guarantee that it only needs to set the first node as the successor node of the original node and break the next reference of the original node.
SOURCE Reading
Queue Build:
PrivateNodeAddwaiter(Node mode) {Node node =NewNode (Thread.CurrentThread(), mode);//Try The fast path of Enq; backup to full Enq on failureNode pred = tail;if(Pred! =NULL) {node.prev= pred;if(Compareandsettail(pred, node)) {pred.Next= node;returnNode } }Enq(node);returnnode;}PrivateNodeEnq(FinalNode node) { for(;;) {Node t = tail;if(T = =NULL) {//Initialization phase if(Compareandsethead(NewNode ())) tail = head; }Else{node.prev= t;if(Compareandsettail(t, node)) {T.Next= node;returnT } } }}Private Final Boolean Compareandsethead(Node Update) {returnUnsafe.Compareandswapobject( This, Headoffset,NULL, update);}Private Final Boolean Compareandsettail(node expect, node update) {returnUnsafe.Compareandswapobject( This, Tailoffset, expect, update);}
First of all, we start with the addWaiter method, this method is to realize the problem of concurrency processing in the form of a spin-free situation. Assuming that there are multiple threads entering this method when initializing, both head and tail have not been initialized and are null, the first thread must have entered the enq(node) method. After entering the enq(node) method, if the head and tail nodes are still not initialized at this point, they will go to the stage of initializing the head and tail nodes, that is, t == null the IF block. This snippet is a CAs that assigns the value of the head to new Node() the returned reference address, and then executes tail=head , at which point the synchronization queue is as follows:
After the first thread enters the enq(final Node node) method's thread after the initialization operation, subsequent loops of the subsequent thread or the first thread are entered into enq the code snippet of the method else .
- When
Node t = tail; node.prev = t the FIFO queue is executed, such as
- After executing
compareAndSetTail(t, node) the FIFO queue, the following conditions are:
- After executing
t.next = node; the FIFO queue, the following conditions are:
- If there is another thread entering into the
enq(final Node node) method, the FIFO queue is as follows:
node wake logic in the synchronization queue :
//1. Exclusive type Public Final Boolean Release(intARG) {if(Tryrelease(ARG)) {//tryrelease (ARG) invokes the implementation of the subclass, letting the subclass decide whether to release the lockNode h = head;if(H! =NULL&& H.Waitstatus!=0)Unparksuccessor(h);return true; }return false;}//2. Shared Type Public Final Boolean releaseshared(intARG) {if(tryreleaseshared(ARG)) {//Call the implementation of the subclass, let the subclass decide whether to release the lock doreleaseshared();return true; }return false;}Private void doreleaseshared() { for(;;) {Node h = head;if(H! =NULL&& h! = tail) {//Sync queue has at least two nodes (head node and business node) intWS = H.Waitstatus;if(ws = = Node.)SIGNAL) {//If the current head node state is signal (implying that subsequent nodes need to wake up) if(!Compareandsetwaitstatus(h, Node.)SIGNAL,0))Continue;//Loop to recheck cases Unparksuccessor(h);the first node to wake up after the head node is awakened}Else if(WS = =0&&!Compareandsetwaitstatus(H,0, Node.PROPAGATE))Continue;//Loop on failed CAS}if(h = = head)//Loop if head changed Break; }}//wake-up of the current node's successorPrivate void Unparksuccessor(Node node) {intWS = node.Waitstatus;if(WS <0)/*** 1. If the current node is still in a valid wait state, revert its state to the initialization state. * 2. Why do you want to restore? You waited, and you waited? Must be restored from the waiting state back! * 3. There is no care to return the value, stating that it is allowed to fail. * 4. This logic is only used when the Cancelacquire method is called, and the other portals pass in the head node .* The state of the head node is 0 here, and it is not believed to look at the method caller. */ Compareandsetwaitstatus(node, WS,0);/*** 1. Purpose of this block logic: Find the first node that is still in a valid wait state and wake it up. * 2. First take the next node of the header, if the node is null or has been canceled, then forward traversal from the tail node to find* Awake nodes. */node s = node.Next;if(s = =NULL|| S.Waitstatus>0) {s =NULL; for(Node t = tail; t! =NULL&& T! = node; t = T.prev)if(T.Waitstatus<=0) s = t; }if(s! =NULL) Locksupport.Unpark(S.Thread);//Call the native method to perform the wake-up thread operation. }
In the Aqs class, tryRelease(int arg) and the tryReleaseShared((int arg)) method body, there is only one line of code: throw new UnsupportedOperationException(); , from here, we can see that Aqs is actually when the decision to release the lock to the AQS specific implementation class to decide, aqs in the implementation of synchronization management, more is to play the role of tool class. Because of this, we are concerned about the synchronous queue to scramble for lock operation, so for other specific details of the temporary attention.
From the above code, we can see in both the exclusive and shared two cases, the release of the lock after the call unparkSuccessor(h); method is the incoming head node, and the unparkSuccessor role of the method is to release the current node's first valid successor node, in this respect, it can be seen that the synchronization queue follows the "FIFO" principle.
The release process of the synchronization queue
//Use this example to illustratePrivate void doacquiresharedinterruptibly(intArgthrowsinterruptedexception {FinalNode node =Addwaiter(Node.SHARED);BooleanFailed =true;Try{ for(;;) {FinalNode p = node.predecessor();if(p = = head) {intR =tryacquireshared(ARG);if(R >=0) {setheadandpropagate(node, r); P.Next=NULL;//help GCFailed =false;return; } }if(Shouldparkafterfailedacquire(p, node) &&Parkandcheckinterrupt())Throw NewInterruptedexception (); } }finally{if(failed)Cancelacquire(node); }}//sync queue out queue and wake logicPrivate void setheadandpropagate(Node node,intPropagate) {Node h = head;//Record old head for check below Sethead(node);if(Propagate >0|| H = =NULL|| H.Waitstatus<0|| (h = head) = =NULL|| H.Waitstatus<0) {node S = node.Next;if(s = =NULL|| S.isShared())doreleaseshared(); }}Private Static Boolean Shouldparkafterfailedacquire(Node pred, node node) {intWS = Pred.Waitstatus;if(ws = = Node.)SIGNAL)return true;if(WS >0) { Do{node.prev= Pred = pred.prev; } while(pred.Waitstatus>0); Pred.Next= node; }Else{Compareandsetwaitstatus(Pred, WS, Node.)SIGNAL); }return false;}Private Final Boolean Parkandcheckinterrupt() {Locksupport.Park( This);returnThread.interrupted();}
The queue-out operation entry for the synchronization queue is actually more than doAcquireSharedInterruptibly this one, and here it's just an example, and the other is similar. When a thread fails to acquire a shared synchronization state, it enters into the doAcquireSharedInterruptibly method, the thread that is currently failing to get the synchronization state is encapsulated as a node, and then detects prev if it is the head node, or if it is a header, the method will be called setHeadAndPropagate , otherwise it will go to shouldParkAfterFailedAcquireand parkAndCheckInterrupt two methods within.
shouldParkAfterFailedAcquireThe method first determines whether the predecessor node of the current node is a valid wait state, or if waitStatus > 0, which is in the canceled state, requires that the predecessor node be removed from the queue. Because do while this method is always looking forward until you find the most recent node that you normally wait for, side-by-step behind it.
Why do I have to find a node that is in a normal state of waiting before it's behind?
Because of the method analyzed above unparkSuccessor , we can know that the queue release wake-up operation, which starts from the head node, releases the successor node of the current node forever, so that if the predecessor node is in the cancel state, the successor node will never be awakened!!! is important to the BOSS!!!
See here is a small partner may ask: if you follow the eldest brother, the boss is KO off to do??
Java Aqs Source Reading