"Java.util.concurrent package source reading" The join of the Fork/join framework

Source: Internet
Author: User

Next look at what happens to the join method that calls Forkjointask:

     Public FinalV Join () {//The Dojoin method returns the status of the task, with three status values://NORMAL, cancelled and exceptional//The wait process for join is performed in the Dojoin method        if(Dojoin ()! =NORMAL)//the Reportresult method has three ways to handle three states of a task://NORMAL: Returns the return value of the Getrawresult () method directly//CANCELLED: Throw cancellationexception//exceptional: Throws the exception if the task execution process throws an exception, otherwise returns Getrawresult ()             returnReportresult (); Else            //Getrawresult are abstract methods that are implemented by subclasses            returnGetrawresult (); }

Recursiveaction and Recursivetask Implement the Getrawresult method.

The recursiveaction is used for situations where there is no return value, so the Getrawresult method returns NULL.

Recursivetask is used for situations where there is a return value, so the return value of the abstract method compute method is returned.

Then continue to see the core method of join Dojoin method:

    Private intDojoin () {Thread T; Forkjoinworkerthread W; intSBooleancompleted; //to invoke join for Forkjoinworkerthread        if(t = thread.currentthread ())instanceofforkjoinworkerthread) {            //the initialization value of the status value is 0, which has been non-negative until the task has been completed//so once the status value becomes negative, it means that the task is complete and returns directly            if((s = status) < 0)                returns; //Check the task stack for the current worker thread (as in LIFO, all this is called a stack)//the top of the stack task is not the current task, if it is, take the task from the stack and execute//then return to the status of the task after execution            if((w = (forkjoinworkerthread) t). Unpushtask ( This)) {                Try{completed=exec (); } Catch(Throwable Rex) {returnSetexceptionalcompletion (Rex); }                if(completed)returnsetcompletion (NORMAL); }            //if it's not a top-of-stack task            returnW.jointask ( This); }        Else            //scenarios where external threads wait for a task to end            returnExternalawaitdone (); }

A few examples from the previous article show how to implement Recursivetask subclasses. In the compute method, you see a call to the Join method, that is, the forkjoinworkerthread call join.

So first look at the implementation of Forkjoinworkerthread 's Jointask method:

    Final intJointask (forkjointask<?>Joinme) {Forkjointask<?> Prevjoin =Currentjoin; Currentjoin=Joinme;  for(ints, retries =max_help;;) {            //The current task is complete, returning to the previous join task            if((s = joinme.status) < 0) {Currentjoin=Prevjoin; returns; }            //If the remaining number of attempts is greater than 0 (max_help value is 16), continue to try            if(Retries > 0) {                if(Queuetop! =queuebase) {                    //Check the task stack of the current thread, if the task stack is not empty, the current task is in the top position of the stack//performs the task returns TRUE, otherwise returns false, directly thinking that the attempt failed                     if(!Localhelpjointask (joinme)) retries= 0; }                //tried half the maximum allowable number of times                Else if(Retries = = Max_help >>> 1) {                    --retries; //checks whether the current task is in the team's first position on a worker thread's task queue//if so, steal the task and execute the task. Trydeqandexec//returns the status value of a task, so greater than or equal to 0 means that the task has not finished executing,//The current thread yields control so that other threads can perform the task                    if(Trydeqandexec (Joinme) >= 0) Thread.yield (); }                Else                    //The Helpjointask method checks whether the current task was stolen by a worker thread,// and is the most recent task stolen by this thread (currentsteal), if so,//The  current thread helps perform this task, and the process returns true if successfulRetries = Helpjointask (joinme)? Max_help:retries-1; }            Else {                //the maximum allowable number of attempts has not been succeeded, reset to try againRetries =Max_help; //one round of unsuccessful attempts to enter the process pool to wait for the taskPool.tryawaitjoin (JOINME); }        }    }

To see what happens when the Tryawaitjoin method of the thread pool is called after a failed attempt:

    Final voidTryawaitjoin (forkjointask<?>Joinme) {        ints; //Clears the current thread's interrupt state before checking whether the task ends
// because Tryawaitdone will call wait may produce interrupt exception
thread.interrupted (); //The task is still in progress, otherwise the execution is completed and returned directly if(joinme.status >= 0) { //blockedcount add 1 to mark the current thread as blocked//Success returns True, otherwise false if(Trypreblock ()) {//call the Wait method to wait for the task to completeJoinme.tryawaitdone (0L); //Blockedcount minus 1, marking the current thread as activePostblock (); } //If the thread is in a closed state, cancel the task Else if(CTL & stop_bit)! = 0L) joinme.cancelignoringexceptions (); } }

Finally, we return to the origin point and see the Tryawaitdone method of task:

    Final voidTryawaitdone (LongMillis) {        ints; Try {            //status is 0, set to 1. It succeeds, and then waits with wait.            if(((s = status) > 0 | |(S= = 0 &&Unsafe.compareandswapint ( This, Statusoffset, 0, SIGNAL)) &&Status> 0) {                synchronized( This) {                    if(Status > 0) Wait (Millis); }            }        } Catch(Interruptedexception IE) {//because wait is interrupted, there is no guarantee that the task will be executed correctly, so when calling the method, be aware that//Check if the task is done}

Walk through the join process within the worker thread, and finally look at what the other thread join waits for, and see the Externalawaitdone method:

    Private intExternalawaitdone () {ints; if((s = status) >= 0) {            Booleaninterrupted =false; synchronized( This) {                //loop wait until task execution ends                 while((s = status) >= 0) {                    if(s = = 0) Unsafe.compareandswapint ( This, Statusoffset,0, SIGNAL); Else {                        Try{wait (); } Catch(Interruptedexception IE) {interrupted=true; }                    }                }            }            //Clear Interrupt Status            if(interrupted) thread.currentthread (). interrupt (); }        returns; }

The Externalawaitdone logic is simpler, in a circular fashion, using the wait method until the end of the task execution.

Since the wait method waits, it is necessary to call the Notify or Notifyall method after the end of the task execution, which is found in the Setcompletion method:

    Private intSetcompletion (intcompletion) {         for(ints;;) {            if((s = status) < 0)                returns; if(Unsafe.compareandswapint ( This, Statusoffset, S, completion)) {                if(s! = 0)                    synchronized( This) {notifyall ();} returncompletion; }        }    }

Here the Fork/join framework is simply finished, because the level is limited, missing a lot of details, you forgive me.

"Java.util.concurrent package source reading" The join of the Fork/join framework

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.