Java CountDownLatch parsing (lower), javacountdownlatch

Source: Internet
Author: User

Java CountDownLatch parsing (lower), javacountdownlatch

  • Preface

In the previous CountDownLatch parsing, we learned about CountDownLatch introduction, CountDownLatch practical scenarios, and the await () method in CountDownLatch implementation principle,

Next, let's take a look at its countDown () method as well as its examples and advantages and disadvantages.

  • CountDownLatch implementation principle

Ii. CountDownLatch. countDown ()

About synchronization queue

When some threads call the await () method, they are suspended in the synchronization queue, and then check whether they can meet the waking conditions (remember that condition? 1. The state is 0, 2, and the node is the first node ),

If this parameter is met, the header node is removed and the next node is set as the header node. For example:

This Node is a static internal class in AbstractQueuedSynchronizer (AQS). It has two attributes:

volatile Node prev;volatile Node next;

Volatile's prev points to the previous node, and volatile's next points to the next node. Of course, if it is a header node, its prev is null, And the next of the End Node is null.

private transient volatile Node head;private transient volatile Node tail;

Head and tail are attributes in AQS, which are used to represent the first and last nodes of the synchronization queue. (If you are interested, you can take a look at transident's serialization keyword, which is not expanded here)

After learning about the synchronization queue, what happened after we started the thread to call the countDown () method? Here we can imagine that the Count value may be less than 1 and the state will be determined to be equal to 0,

If it is not equal to 0, the thread will continue to go down; if it is equal to 0, it may need to wake up this group of suspended threads.

In the end, isn't it like this? Let's continue with the author to find the source code.

public void countDown() {   sync.releaseShared(1);}

After CountDownLatch. countDown () is called, it calls the releaseShared () method of the internal class instance of Sync.

Public final boolean releaseShared (int arg) {if (tryReleaseShared (arg) {doReleaseShared (); return true; // exit this method} return false; // exit this method}

There is no releaseShared () method in the Sync class, so it should be inheritance and AQS. We can see that there are only two ways to exit the AQS method. If the tryReleaseShared (arg) condition is true, execute a doReleaseShared () Exit. If the condition is false, exit directly.

Like our guess, this condition is probably the determination of whether the state is 0... Next let's take a look.

Protected boolean tryReleaseShared (int releases) {for (;) {// endless loop int c = getState (); // obtain the state value in the primary storage if (c = 0) // if the state is 0, exit return false; int nextc = C-1; // subtract one to prepare cas to update the value if (compareAndSetState (c, nextc )) // cas update return nextc = 0; // If the update is successful, the system determines whether to exit. If the update fails, the for loop continues until the thread is concurrently updated }}

We can see that four or more lights are surging out of our minds. Our guess is correct!

Private void doReleaseShared () {for (;) {// It is an endless loop Node h = head; if (h! = Null & h! = Tail) {int ws = h. waitStatus; if (ws = Node. SIGNAL ){
 // If the current node is SIGNAL, it means that it is waiting for a SIGNAL,
 Or it is waiting to be awakened, so do two things: 1 is to reset the waitStatus flag, 2 is to wake up the next node after the reset is successful. If (! CompareAndSetWaitStatus (h, Node. SIGNAL, 0) continue; unparkSuccessor (h);} else if (ws = 0 &&! CompareAndSetWaitStatus (h, 0, Node. PROPAGATE) // If the waitStatus of the header Node is reset (waitStatus = 0), set it to "propagation. This means that the status needs to be propagated to a node. Continue;} if (h = head) break ;}}

Students (knocking on the blackboard ...), why should we execute this method? Because the state is already 0, we should set the thread status in the synchronization queue to the shared state (Node. PROPAGATE, default status ws = 0), and spread backward to achieve State sharing.

This is why the method name has a shared state, because the shared state needs to be propagated, rather than a node (thread) exclusive. Look at this endless loop. There is only one exit path, that is, h = head, that is, the thread is the first node and the status is shared.

Here again, the reader may ask, the state is already equal to 0, and we also set the state of the head node to the sharing state through a loop, but how does it wake up? Now, let's look at the code in the previous article again.

Private void doAcquireSharedInterruptibly (int arg) throws InterruptedException {final Node node = addWaiter (Node. SHARED); // Add the node boolean failed = true to the synchronization queue; try {(;;) {// an endless loop jumps out of the loop only through the following two methods: final Node p = node. predecessor (); // The first node of the current thread if (p = head) {// if it is the first node int r = tryAcquireShared (arg ); // do you have any familiarity with this? See above if (r> = 0) {setHeadAndPropagate (node, r); // process subsequent node p. next = null; // help GC this can be referenced by failed = false; return; // The Count value is 0 and the loop exists for the header node} if (shouldParkAfterFailedAcquire (p, node) & parkAndCheckInterrupt () throw new InterruptedException (); // response interrupt loop} finally {if (failed) cancelAcquire (node ); // remove the synchronization queue node if it is interrupted and exited }}

This is the threads suspended in the synchronization queue. They spin to check whether they meet the conditions and wake up (state = 0, and is the header node). If yes, the setHeadAndPropagate method will be called.

 private void setHeadAndPropagate(Node node, int propagate) {     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();    }
}

This method sets the next node of the current node as the header node and also calls the doReleaseShared method, this method sets the header node to the shared state. As a result, the shared state is propagated.

So far, the countDown () method in the CountDownLatch implementation principle is over.

  • CountDownLatch example

If you don't talk much about it, go directly to the Code:

Package com. test. demo; import java. util. concurrent. countDownLatch;/*** @ Title: TestCountDownLatch. java * @ Describe: * @ author: Mr. yanphet * @ Email: mr_yanphet@163.com * @ date: September 18, 2016 11:22:42 * @ version: 1.0 */public class TestCountDownLatch {private static final int taskNum = 5; static class MyRunnable implements Runnable {private int num; private CountDownLatch cdl; public MyRunnable (int num, CountDownLatch cdl) {this. num = num; this. cdl = cdl;} public void run () {System. out. println ("Number" + num + "Threads start to execute the task... "); try {Thread. sleep (5*1000); // simulate task time consumption} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("Number" + num + "thread task execution ends... "); cdl. countDown () ;}} public static void main (String [] args) {CountDownLatch cdl = new CountDownLatch (taskNum); for (int I = 1; I <= taskNum; I ++) {MyRunnable mr = new MyRunnable (I, cdl); Thread t = new Thread (mr); t. start ();} System. out. println ("Wait until other threads finish the task before continuing to execute... "); try {cdl. await ();} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("other threads complete the task, the main thread starts to execute... "); System. out. println ("the main thread task is completed, and the entire task progress is completed... ");}}

The execution result is as follows:

4th threads start to execute the task... 5th threads start to execute the task... 3rd threads start to execute the task... 2nd threads start to execute the task... 1st threads start to execute the task... wait until other threads finish the task before continuing to execute... the execution of the 4th thread tasks is completed... the execution of the 2nd thread tasks is completed... the execution of the 1st thread tasks is completed... the execution of the 3rd thread tasks is completed... the execution of the 5th thread tasks is completed... when other threads complete the task, the main thread starts to execute... the main thread task is completed, and the entire task progress is completed...

The main thread waits for five subthreads to finish the task before continuing to execute its own task.

  • Advantages and disadvantages of CountDownLatch

Advantages:

The advantages of CountDownLatch are beyond doubt. for users, you only need to input an int variable to control the number of tasks. As for the maintenance of synchronization queues, maintenance of state variable values is transparent to users and convenient to use.

Disadvantages:

CountDownLatch cannot be changed or used cyclically after the state is set.

The above is all about CountDownLatch learning. Because the author is also a cainiao, it is inevitable to repeat the source code from the perspective of cainiao. If you have any questions, I hope you can correct them. Thank you ~~~

 

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.