併發系列(二)——FutureTask類原始碼簡析

王大咩的圖書館發表於2020-07-25

背景

  本文基於JDK 11,主要介紹FutureTask類中的run()、get()和cancel() 方法,沒有過多解析相應interface中的註釋,但閱讀原始碼時建議先閱讀註釋,明白方法的主要的功能,再去看原始碼會更快。

  文中若有不正確的地方歡迎大夥留言指出,謝謝了!

1、FutureTask類圖

  1.1 FutureTask簡介

  FutureTask類圖如下(使用IDEA生成)。如圖所示,FutureTask實現了Future介面的所有方法,並且實現了Runnable介面,其中,Runnable介面的現實類用於被執行緒執行,而Future代表的是非同步計算的結果。因此,FutureTask類可以理解為,執行run()(實現Runnable介面中的方法),通過Future的get()方法獲取結果。

  1.2 FutureTask的屬性

 //任務執行緒總共有七中狀態如下:
    * 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 CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

    /** The underlying callable; nulled out after running */
    //在run()方法中呼叫
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    //任務執行結果,callable.call()正常執行的返回值
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    //任務執行緒
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    //等待任務結果的執行緒組成的節點,放在連結串列對列中
    private volatile WaitNode waiters;

 2、原始碼解析

  2.1 run()方法

public void run() {
        //1、若是任務的狀態不是NEW,且使用CAS將runner置為當前執行緒則直接返回
        if (state != NEW ||
            !RUNNER.compareAndSet(this, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            //2、任務不為null,且state的狀態為NEW的情況下才執行任務
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //執行任務並接收執行結果
                    result = c.call();
                    //正常執行結果則將標識置為true
                    ran = true;
                } catch (Throwable ex) {
                    //3、任務發生異常,執行或cancel(),則結果置為null,並記錄異常資訊
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //4、任務正常結束,則設定返回結果
                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;
            //5、若是異常導致,走另一個流程
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

  1)若任務的狀態不是NEW,或者使用CAS將runner置為當前執行緒失敗,則直接返回的原因是防止多執行緒呼叫;

  2)再度確認任務執行的前置條件;

  3)任務執行異常,將result置為null,並記錄異常,setException()原始碼如下:

protected void setException(Throwable t) {
        //使用CAS將狀態置為中間態COMPLETING
        if (STATE.compareAndSet(this, NEW, COMPLETING)) {
            outcome = t;
            STATE.setRelease(this, EXCEPTIONAL); // final state
            //任務處於結束態時,遍歷喚醒等待result的執行緒
            finishCompletion();
        }
    }

  任務的狀態變化為NEW  - >  COMPLETING  ->  EXCEPTIONAL

  4)任務正常結果則會設定result之後,喚醒waitNode的連結串列對列中等待任務結果的執行緒;

  5)異常後的呼叫邏輯如下:

 //保證呼叫cancel在run方法返回之前中斷執行任務
    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)
            //當前執行緒讓出CPU執行權
                Thread.yield(); // wait out pending interrupt
    }

   2.2  get()方法

  原始碼分析如下:

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            //等待任務完成
            s = awaitDone(false, 0L);
        //返回結果
        return report(s);
    }

  其中,等待過程分析如下:

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        // The code below is very delicate, to achieve these goals:
        // - call nanoTime exactly once for each call to park
        // - if nanos <= 0L, return promptly without allocation or nanoTime
        // - if nanos == Long.MIN_VALUE, don't underflow
        // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
        //   and we suffer a spurious wakeup, we will do no worse than
        //   to park-spin for a while
        long startTime = 0L;    // Special value 0L means not yet parked
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            int s = state;
            //1、任務的狀態已經處於最終的狀態,則將任務執行緒的引用置為null,直接返回狀態
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //2、任務的狀態為COMPLETING說明任務已經接近完成,則當前執行緒讓出CPU許可權以便任務執行執行緒獲取到CPU執行權
            else if (s == COMPLETING)
                // We may have already promised (via isDone) that we are done
                // so never return empty-handed or throw InterruptedException
                Thread.yield();
            //3、當前執行緒被中斷,則將當前執行緒從等待任務結果的對列中移除,並丟擲異常
            else if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }
            //4、任務執行緒的狀態小於COMPLETING,則將當前呼叫get()方法的執行緒新建一個Node
            else if (q == null) {
                if (timed && nanos <= 0L)
                    return s;
                q = new WaitNode();
            }
            //5、若由當前執行緒構成的Node未加入連結串列中,則加入
            else if (!queued)
                queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
            //6、是否開啟了超時獲取結果
            else if (timed) {
                final long parkNanos;
                if (startTime == 0L) { // first time
                    startTime = System.nanoTime();
                    if (startTime == 0L)
                        startTime = 1L;
                    parkNanos = nanos;
                } else {
                    long elapsed = System.nanoTime() - startTime;
                    //7、超時則從棧中移除當前執行緒
                    if (elapsed >= nanos) {
                        removeWaiter(q);
                        return state;
                    }
                    parkNanos = nanos - elapsed;
                }
                // nanoTime may be slow; recheck before parking
                //當前執行緒掛起
                if (state < COMPLETING)
                    LockSupport.parkNanos(this, parkNanos);
            }
            else
                LockSupport.park(this);
        }
    }

  獲取到返回的狀態值後,根據其狀態值判斷是返回結果還是丟擲異常。

  2.2 cancel()方法

public boolean cancel(boolean mayInterruptIfRunning) {
        //1、若任務執行緒的狀態為NEW,則將其狀態從NEW置為INTERRUPTING、CANCELLED
        if (!(state == NEW && STATE.compareAndSet
              (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            //CAS改變任務執行緒的狀態失敗,則直接返回false,表示cancel失敗
            return false;
        try {    // in case call to interrupt throws exception
            //2、改變任務執行緒的狀態成功後,根據是否中斷running的任務執行緒的標識位,決定是否中斷正在執行的任務執行緒
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    //任務執行緒不為null,則使用interrupt()中斷
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    //設定狀態
                    STATE.setRelease(this, INTERRUPTED);
                }
            }
        } finally {
            //3、清理等待任務結果的等待執行緒
            finishCompletion();
        }
        return true;
    }

 3、總結

  1)執行run()方法,是在呼叫在Callable的call()方法,其實在初始化時被指定;

  2)呼叫get()方法,若是任務執行緒還在執行,則會把呼叫get的執行緒封裝成waitNode塞入到FutureTask類內部的阻塞連結串列對列中,可以有多個執行緒同時呼叫get()方法;

  3)cancel()方法是通過對任務執行緒呼叫interrupt()實現;

相關文章