FutureTask 解析

Reference from:  https://www.cnblogs.com/linghu-java/p/8991824.html

 

Future interface represents the result of an asynchronous computation future by providing a method of asynchronous computation can check whether completed or wait for the results and get the results, but also can cancel the execution.

Calculation is represented by a callable futureTask achieved. There are three states: waiting to run, running, running to complete. Implementation of the completion of the calculation represents the end of all possible ways, including normal end, due to the cancellation and the end, due to abnormal ends.

Future.get behavior depends on the state of the task.

Executor FutureTask indicating an asynchronous frame in the task, can also be used in addition represent long computation some time, these calculations can be started before the results.

FutureTask is the future implementation class.

FutureTask realized RunnableFuture, runnableFuture interface inherits from Runnable, Future

Member variables:

/ * * 
 * At The RUN State of the this Task, INITIALLY NEW. At The RUN State 
 * transitions to A Terminal State only in Methods the SET, 
 * setException, and the Cancel. During Completion, State May the Take ON 
 * transient values of the COMPLETING (the while outcome IS being the SET) or 
 * interrupting (only the while interrupting at The Runner to Satisfy A 
 * the Cancel (to true)). Transitions from THESE Intermediate to Final 
 * States use Cheaper ordered / lazy Writes Because values are UNIQUE 
 * and CAN not BE Further Modified. 
 
 State indicates that the task operating state, is initially new. Only call set, setException, and cancel methods, running over to the state to terminate the state. 
 During the task, the state relies on completing (when the outcome is set) or be interrupted (interrupted only when the runner to meet a canceled event). Delayed write ordered from the intermediate to the final state of the excessive use inexpensive. 
 Because these values are unique. And the future can not be changed.
 
 *
 * Possible state transitions:
 * NEW -> COMPLETING -> NORMAL
 * NEW -> COMPLETING -> EXCEPTIONAL
 * NEW -> CANCELLED
 * NEW -> INTERRUPTING -> INTERRUPTED
 */
private volatile int state;
private static final int NEW          = 0;
private static final int COMPLETING   = 1;
private static final int NORMAL       = 2;
private static final int EXCEPTIONAL  = 3;
Private  static Final int CANCELED = . 4 ;
 Private  static Final int Interrupting = . 5 ;
 Private  static Final int an INTERRUPTED = . 6 ; 

/ * * the underlying of The Callable; Nulled After running OUT * / 
// potential running thread, is disposed after the operation as null 
Private a Callable <V> a Callable;
 // this is the return value of the thread to run after the save. Can be normal or abnormal return information 
/ * * the Result to return or at The Exception to the throw from GET () * / 
Private Object outcome; //-volatile non, protected by State reads / Writes
 // actual thread running callable objects. 
/ * * The running of The Thread Callable; cased During RUN () * / 
Private  volatile the Thread Runner;
 // 
/ * * Treiber Stack of Waiting Threads * / 
Private  volatile WaitNode Waiters; 

public  void RUN () {
 // determine the state is not the new, if it is new, then try to save in the current thread runner field. 
    IF (! State NEW = || 
        UNSAFE.compareAndSwapObject (! the this , runnerOffset,
                                      null , Thread.currentThread ()))
         return ;
    the try { 
        a Callable <V> C = Callable;
         IF (! C = null && State == NEW) { 
            V Result; 
            Boolean RAN; 
            the try {
                 // perform successfully, the normal value Return 
                Result = c.call (); 
                RAN = to true ; 
            } the catch (the Throwable EX) {
                 // fails, there is an abnormality in the implementation of the process, the result is null, ran as false, and sets the abnormality information. 
                = Result null ; 
                RAN = to false ;
                setException(ex);
            }
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

/**
 Report to the this future Causes * {@link AN ExecutionException} 
 * with Throwable The GIVEN AS ITS the cause is, The unless the this future has 
 * has been already been SET or Canceled. 
 * 
 So forth thrown future, unless future has been set up abnormal or was canceled. 
 
 * <P> This internally by the Invoked Method The IS #run} {@link Method 
 * upon failure of The Computation. 
 * 
 * @Param T The failure of the cause is 
 * / 
protected  void setException (the Throwable T) {
     // this sentence meaning that if the state of the current thread is new, so the new into completing, and returns true, it continues to execute code inside the brackets if, on the contrary, is directly returned, if the code is not executed. 
    IF (UNSAFE.compareAndSwapInt ( the this , stateOffset, NEW, the COMPLETING)) {
         // the outcome provided to the exception.
        = outcome T;
         // is to change the current state of the abnormal state. 
        UNSAFE.putOrderedInt ( the this , stateOffset, EXCEPTIONAL); // Final State
         // After an abnormal state is arranged to do the associated operation completion status. 
        finishCompletion (); 
    } 
} 

/ * * 
 * All Signals Removes and Waiting Threads, Invokes DONE (), and 
 * OUT NULLS Callable. 
 
 Clear all waitNode. And wake up all waiting threads, done execution method. 
 * / 
Private  void finishCompletion () {
     // Assert State> the COMPLETING; 
    for (Q WaitNode; (Waiters Q =) =! Null ;) {
         //Determine the current is not waitnode q, if so, then the current change waitnode null, and return true. 
        IF (UNSAFE.compareAndSwapObject ( the this , waitersOffset, Q, null )) {
             // by the spin. Is dead cycle to the waitNode the threads are set to null 
            for (;;) { 
                the Thread t = q.thread;
                 IF (t =! Null ) { 
                    q.thread = null ;
                     // wake-up thread. 
                    LockSupport.unpark (T); 
                } 
                WaitNode Next = q.next;
                 IF (Next == null)
                     BREAK ; 
                q.next = null ; // The unlink Help GC to 
                Q = Next; 
            } 
            BREAK ; 
        } 
    } 
    // perform done method, is done empty method, if we want to customize this, can override this method. 
    DONE (); 

    Callable = null ;         // to footprint of the reduce 
} 

/ * * 
 * Makes Available The GIVEN The Thread for the permit, IF IT 
 . * The WAS the If Not Available Thread already blocked WAS ON 
 *} {@code Park Will the then IT unblock. Otherwise, its next call
 Park} to {@code * IS Guaranteed not to Block. This Operation
 Guaranteed to have have not IS * the any Effect at The IF GIVEN AT All 
 * the Thread has not been Started. 
 * 
 If you have not yet given thread is available, so this thread is available. If a thread is blocked in a park way, then it will become blocked. Otherwise, guaranteed not to be blocked when a call park next method. If the thread is not started, this operation can guarantee no effect. 
 
 In fact, this thread is to wake up, do not let it wait. 
 
 The Thread to @param Thread * to unpark, or @code {null}, Case in Which 
 * has the this Operation Effect NO 
  
 * When the Invoked Protected Method transitions to the this Task State* / 
public  static  void to unpark (the Thread Thread) {
     IF (Thread =! Null )
         the unsafe .unpark (Thread); 
} 

/ * * 
 *} {@code isDone (Whether or Via Normally cancellation). of The 
 * default Implementation Nothing does. On May the override Subclasses
 * The this Method, to the Invoke Completion the callbacks or the perform 
 * Bookkeeping. Note that you CAN Query Status Inside at The 
 * Implementation of the this Method, to the Determine model types within the this Task 
 * has been Canceled. 
 
 Protected method when the task changes state when done to be called, regardless It is normally completed or was canceled. The default implementation does nothing. Subclasses can override this method to perform recording or callback call completion. 
 Note that you can query status inside the implementation of this method to determine whether the task was canceled. 
 
 * / 
Protected  void DONE () {} 

/ * * 
 * Ensures that the any interrupt from A Possible the Cancel (to true) IS only 
 * A Task delivered to the while in RUN or runAndReset. 
 
 Guarantee from a possible cancellation of events can only be interrupted when publishing or run at run time to a task and reset. 
 * / 
Private  void handlePossibleCancellationInterrupt ( int S) {
    // It is possible for our interrupter to stall before getting a
    // chance to interrupt us.  Let's spin-wait patiently.
    if (s == INTERRUPTING)
        while (state == INTERRUPTING)
            Thread.yield(); // wait out pending interrupt

    // assert state == INTERRUPTED;

    // We want to clear any interrupt we may have received from
    // cancel(true).  However, it is permissible to use interrupts
    // as an independent mechanism for a task to communicate with
    // its caller, and there is no way to clear only the
    // cancellation interrupt.
    //
    // Thread.interrupted();
}
View Code

 

Guess you like

Origin www.cnblogs.com/liumy/p/11607423.html