Java concurrency series [3] ---- sharing mode of AbstractQueuedSynchronizer source code analysis,

Source: Internet
Author: User

Java concurrency series [3] ---- sharing mode of AbstractQueuedSynchronizer source code analysis,

Through the analysis in the previous article, we learned that there are three methods to obtain the lock in the exclusive mode, namely, obtaining the lock without responding to thread interruption, obtaining the response thread interruption, and setting the timeout time to get the lock. There are also three methods to obtain locks in the shared mode, which are basically the same. We have figured out one way to quickly understand other methods. Although AbstractQueuedSynchronizer has more than one thousand lines of source code, there are many duplicates, so readers should not be scared at the beginning, as long as they are able to see it slowly and naturally gradually comprehend. In my personal experience, there are several key points for reading the AbstractQueuedSynchronizer source code: the difference between the exclusive mode and the sharing mode, the waiting status of nodes, understanding of the condition queue. After understanding these key points, the subsequent source code reading will be much easier. Of course, these are detailed descriptions in my article titled Java concurrent series [1] ---- brief actqueuedsynchronizer source code analysis. You can check them first. This article analyzes the Shared Mode in three ways to obtain the lock and release the lock.

1. Do not respond to thread interruption acquisition

1 // obtain the lock in non-disruptive mode (shared mode) 2 public final void acquireShared (int arg) {3 // 1. try to get the lock 4 if (tryAcquireShared (arg) <0) {5 // 2. if the acquisition fails, go to this method 6 doAcquireShared (arg); 7} 8} 9 10 // try to get the lock (share mode) 11 // negative number: 12 // zero: the current node is successfully obtained, but the subsequent node cannot get 13 // positive: the current node is successfully obtained, in addition, the successor node can also obtain the successful 14 protected int tryAcquireShared (int arg) {15 throw new UnsupportedOperationException (); 16}

The acquireShared method is used to obtain the lock without responding to thread interruption. In this method, call tryAcquireShared to try to obtain the lock. The tryAcquireShared method returns a status for obtaining the lock. AQS specifies that if the return status is negative, the current node fails to obtain the lock, if the value of 0 indicates that the current node has successfully obtained the lock, but the subsequent node cannot obtain the lock. If the positive number is used, the current node has successfully obtained the lock, and the subsequent node can also obtain the lock. When sub-classes implement the logic of the tryAcquireShared method to obtain the lock, the return value must follow this convention. If the return value of tryAcquireShared is less than 0, it indicates that the attempt to obtain the lock failed. Next, call the doAcquireShared method to add the current thread to the synchronization queue. We can see the doAcquireShared method.

1 // get in synchronization Queue (share mode) 2 private void doAcquireShared (int arg) {3 // Add to synchronization queue 4 final Node node = addWaiter (Node. SHARED); 5 boolean failed = true; 6 try {7 boolean interrupted = false; 8 (;;) {9 // obtain the frontend Node 10 final node p = Node of the current node. predecessor (); 11 // if the forward node is the head node, try again to get the lock 12 if (p = head) {13 // try again to get the lock and return the retrieval status 14 // r <0, indicating that the acquisition failed 15 // r = 0, indicating that the current node has been obtained successfully, however, the successor node cannot get 16 // r> 0, indicating that the current node is successfully obtained, and the successor node can also get 17 int r = tryAcquireShared (arg ); 18 if (r> = 0) {19 // It indicates that the current node has successfully obtained the lock. At this time, it will spread the lock status information to the successor node 20 setHeadAndPropagate (node, r); 21 p. next = null; 22 // if the interrupt request is received during thread congestion, the request is responded to in this step 23 if (interrupted) {24 selfInterrupt (); 25} 26 failed = false; 27 return; 28} 29} 30 // each time the lock fails to be obtained, the system determines whether the thread can be suspended, if possible, the thread will be suspended in the parkAndCheckInterrupt Method 31 if (shouldParkAfterFailedAcquire (p, node) & parkAndCheckInterrupt () {32 interrupted = true; 33} 34} 35} finally {36 if (failed) {37 cancelAcquire (node); 38} 39} 40}

To enter the doAcquireShared method, call the addWaiter method to package the current thread as a node and put it at the end of the synchronization queue. We will talk about the process of adding nodes when talking about the exclusive mode. After the node enters the synchronization queue, if it finds that the node before it is the head node, because the thread of the head node has obtained the lock and entered the room, then the next node to obtain the lock will be its turn, so the current node will not suspend itself, but will try again to get the lock, if the previous person just releases the lock and leaves, then the current node can successfully obtain the lock. If the previous user has not released the lock, the shouldParkAfterFailedAcquire method will be called. In this method, the head node status will be changed to SIGNAL, only when the status of the previous node is SIGNAL can the current node safely suspend itself, and all threads will be suspended in the parkAndCheckInterrupt method. If the current node happens to have successfully obtained the lock, it will call the setHeadAndPropagate method to set itself as the head node and wake up the nodes that are also in shared mode. Next, let's take a look at the specific operations of the setHeadAndPropagate method.

1 // set the head Node and spread the lock state (share mode) 2 private void setHeadAndPropagate (node Node, int propagate) {3 Node h = head; 4 // set the given node to head node 5 setHead (node ); 6 // if propagate is greater than 0, the lock can be obtained 7 if (propagate> 0 | h = null | h. waitStatus <0) {8 // obtain the successor Node of the given node 9 Node s = node. next; 10 // if the successor node of the given node is null, or its status is shared status 11 if (s = null | s. isShared () {12 // wake up successor node 13 doReleaseShared (); 14} 15} 16} 17 18 // unlock operation (share mode) 19 privat E void doReleaseShared () {20 for (;) {21 // get the head Node of the synchronization queue 22 Node h = head; 23 if (h! = Null & h! = Tail) {24 // get the waiting status of the head node 25 int ws = h. waitStatus; 26 // if the head Node is in the SIGNAL status, it indicates that someone is waiting in queue for 27 if (ws = Node. SIGNAL) {28 // first update the waiting state of the head node to 029 if (! CompareAndSetWaitStatus (h, Node. SIGNAL, 0) {30 continue; 31} 32 // wake up the successor node 33 unparkSuccessor (h); 34 // if the head node status is 0, it indicates that no one is waiting in the queue at this time, and the head state is changed to PROPAGATE35} else if (ws = 0 &&! CompareAndSetWaitStatus (h, 0, Node. PROPAGATE) {36 continue; 37} 38} 39 // The loop 40 if (h = head) {41 break can be exceeded only when the head node is not modified during the period; 42} 43} 44}

Call the setHeadAndPropagate method to first set itself to the head node, and then decide whether to wake up the successor Node Based on the returned value of the input tryAcquireShared method. As mentioned above, when the return value is greater than 0, it indicates that the current node has successfully obtained the lock, and the subsequent node can also successfully obtain the lock. At this time, the current node needs to wake up the nodes in the sharing mode. Note that each wake-up only wakes up the last node. If the last node is not in the sharing mode, the current node directly enters the room and does not wake up the later node. In shared mode, operations to wake up the successor node are performed in the doReleaseShared method. The wake-up operations in Shared Mode and exclusive mode are basically the same, all are to find the sign (waiting status) on your seat. If the sign is SIGNAL, it indicates that someone needs to wake it up. If the sign is 0, it indicates that no one is waiting in the queue at this time. In the exclusive mode, if no one is in the queue, they will directly Leave the queue. In the shared mode, if no one is in the queue after the queue, the current node will still leave a small note (set the wait state to PROPAGATE) before leaving to tell the later people the locks can be acquired. Then, when trying to obtain the lock, the person next to the lock can determine whether to directly obtain the Lock Based on the lock status.

2. Response thread interruption acquisition

1 // obtain the lock (share mode) in an interrupt mode 2 public final void acquireSharedInterruptibly (int arg) throws InterruptedException {3 // first judge whether the thread is interrupted, if yes, an exception is thrown. 4 if (Thread. interrupted () {5 throw new InterruptedException (); 6} 7 // 1. try to get the lock 8 if (tryAcquireShared (arg) <0) {9 // 2. if the retrieval fails, enter the method 10 doAcquireSharedInterruptibly (arg); 11} 12} 13 14 // get in break mode (share mode) 15 private void doAcquireSharedInterruptibly (int arg) throws InterruptedException {16 // Insert the current Node into the end of the synchronization queue 17 final node Node = addWaiter (Node. SHARED); 18 boolean failed = true; 19 try {20 for (;) {21 // obtain the front-end Node 22 final node p = Node of the current node. predecessor (); 23 if (p = head) {24 int r = tryAcquireShared (arg); 25 if (r> = 0) {26 setHeadAndPropagate (node, r ); 27 p. next = null; 28 failed = false; 29 return; 30} 31} 32 if (shouldParkAfterFailedAcquire (p, node) & parkAndCheckInterrupt ()) {33 // If the thread receives an interrupt request during the blocking process, it will immediately throw an exception here 34 throw new InterruptedException (); 35} 36} 37} finally {38 if (failed) {39 cancelAcquire (node); 40} 41} 42}

The method for obtaining a lock from a response thread interrupt is basically the same as that for obtaining a lock from a non-response thread interrupt. The only difference is where to respond to the thread's interrupt request. When the thread does not respond to thread interruption to obtain the lock, the thread is awakened from the parkAndCheckInterrupt method, and immediately returns whether to receive the interrupt request after waking up, even if an interrupt request is received, it will continue to spin until it gets the lock and then respond to the interrupt request and suspend itself. When the response thread gets the lock, the thread will immediately respond to the interrupt request after being awakened. If the thread is interrupted during the blocking process, an InterruptedException exception will be thrown immediately.

3. Set the timeout value.

1 // get the lock (share mode) by specifying the timeout value. 2 public final boolean tryAcquireSharedNanos (int arg, long nanosTimeout) throws InterruptedException {3 if (Thread. interrupted () {4 throw new InterruptedException (); 5} 6 // 1. call tryAcquireShared to try to obtain the lock 7 // 2. call doAcquireSharedNanos 8 return tryAcquireShared (arg)> = 0 | doAcquireSharedNanos (arg, nanosTimeout); 9} 10 11 // obtain the lock in the Shared Mode for a limited timeout period) 12 private boolean doAcquireSharedNanos (int arg, long nanosTimeout) throws InterruptedException {13 long lastTime = System. nanoTime (); 14 final Node node = addWaiter (Node. SHARED); 15 boolean failed = true; 16 try {17 for (;) {18 // get the front Node 19 final node p = Node of the current node. predecessor (); 20 if (p = head) {21 int r = tryAcquireShared (arg); 22 if (r> = 0) {23 setHeadAndPropagate (node, r ); 24 p. next = null; 25 failed = false; 26 return true; 27} 28} 29 // If the timeout time is used up, 30 if (nanosTimeout <= 0) {31 return false; 32} 33 // 1. check whether the thread suspension requirement is met (ensure that the frontend node status is SIGNAL) 34 // 2. check whether the timeout value is greater than the spin time 35 if (shouldParkAfterFailedAcquire (p, node) & nanosTimeout> spinForTimeoutThreshold) {36 // if the above two conditions are met, the current thread will be suspended for a period of time 37 LockSupport. parkNanos (this, nanosTimeout); 38} 39 long now = System. nanoTime (); 40 // time-out time minus the time for obtaining the lock 41 nanosTimeout-= now-lastTime; 42 lastTime = now; 43 // if an interrupted request is received during blocking, an exception is immediately thrown. 44 if (Thread. interrupted () {45 throw new InterruptedException (); 46} 47} 48} finally {49 if (failed) {50 cancelAcquire (node); 51} 52} 53}

If you understand the above two methods, it will be easy to set the timeout time. The basic process is the same, mainly to understand the timeout mechanism. If the lock fails to be obtained for the first time, the doAcquireSharedNanos method will be called and the timeout time will be passed in. After Entering the method, the lock will be obtained again based on the situation. If the lock fails again, the thread will be suspended. At this time, it will determine whether the timeout time is greater than the spin time. If yes, the thread will be suspended for a period of time; otherwise, it will continue to try to get it, each time a lock is acquired, the timeout value is subtracted from the time when the lock is obtained. This continues until the timeout time is exhausted. If the lock is not obtained, the acquisition ends and a failed identifier is returned. During this period, the thread is responding to thread interruption.

4. node team-out operations in Shared Mode

1 // unlock operation (share mode) 2 public final boolean releaseShared (int arg) {3 // 1. try to release lock 4 if (tryReleaseShared (arg) {5 // 2. if the release succeeds, the other thread 6 doReleaseShared (); 7 return true; 8} 9 return false; 10} 11 12 // tries to release the lock (share mode) 13 protected boolean tryReleaseShared (int arg) {14 throw new UnsupportedOperationException (); 15} 16 17 // unlock operation (share mode) 18 private void doReleaseShared () {19 for (;) {20 // get head Node 21 Node h of the synchronization queue = Head; 22 if (h! = Null & h! = Tail) {23 // get the head node Wait Status 24 int ws = h. waitStatus; 25 // if the head Node is in the SIGNAL status, it indicates that someone is waiting in queue for 26 if (ws = Node. SIGNAL) {27 // first update the waiting state of the head node to 028 if (! CompareAndSetWaitStatus (h, Node. SIGNAL, 0) {29 continue; 30} 31 // wake up the successor node 32 unparkSuccessor (h); 33 // if the head node status is 0, it indicates that no one is waiting in the queue at this time, and the head state is changed to PROPAGATE34} else if (ws = 0 &&! CompareAndSetWaitStatus (h, 0, Node. PROPAGATE) {35 continue; 36} 37} 38 // The loop 39 if (h = head) {40 break can be exceeded only when the head node is not modified during the period; 41} 42} 43}

After the thread finishes the work in the room, it will call the releaseShared method to release the lock. First, call the tryReleaseShared method to try to release the lock. The judgment logic of this method is implemented by the subclass. If the release succeeds, call the doReleaseShared method to wake up the successor node. After going out of the room, it will find the original seat (head node) and check whether there is a small note in the seat (the status is SIGNAL). If there is one, it will wake up the successor node. If there is no (the status is 0), it means that no one in the queue is in the queue. before leaving, it will do the last thing: Leave a small note in its seat (the status is set to PROPAGATE ), the last step is the only difference between the entire lock release process and the exclusive mode.

Note: All the above analyses are based on JDK1.7. Different versions may differ.

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.