Java并發包FutrueTask詳解

Java并發包FutureTask詳解

我們已經知道了所有提交給jdk線程池的任務都會被封裝成一個FutureTask對象。線程池執行的其實是FutureTask中的run方法。

類圖

image.png

可以看到FutureTask實現了Future和Runnable兩個接口,說明它既可以當做任務提交給線程池,也可作為Future查詢任務執行情況或者是取消任務。

成員變量

     /* 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;

這是用于定義任務狀態的變量。

  • 0-初始
  • 1-執行中
  • 2-已完成
  • 3-異常
  • 4-已取消
  • 5-中斷中
  • 6-被中斷
/** The underlying callable; nulled out after running */
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    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;
  • callable-就是我們傳遞進來的原始的任務
  • outcome-任務執行的結果
  • runner-執行該任務的線程
  • waiters-等待任務完成的線程

構造函數

public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

FutureTask一共有兩個構造函數,第一個構造函數接收一個Callable對象,第二個構造函數接收一個Runnable對象和一個泛型對象result,這個構造函數中調用Executors的callable方法將Runnable對象包裝成一個Callable對象。

Executors的callable方法核心如下:

static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }

這是將Runnable轉化為Callable對象的過程,其實很簡單,由于Runnable并沒有返回值,而Callable需要返回值,因此就直接拿我們傳遞的result作為返回值了。

注意到,構造函數中將任務的狀態置為NEW。

成員函數

    public boolean isCancelled() {
        return state >= CANCELLED;
    }

    public boolean isDone() {
        return state != NEW;
    }

第一個方法判斷任務是否已經被取消了。可以看到4,5,6狀態均視為已取消。

第二個方法判斷任務是否已經完成。只要不是初始狀態都視為已完成

public boolean cancel(boolean mayInterruptIfRunning) {
        //如果state==NEW,說明任務還沒開始,此時只需要根據傳遞的參數將其狀態置為中斷中或者已取消即可
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        //任務并不是初始狀態,說明已經開始執行了
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                  //嘗試中斷
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    //將狀態置為已中斷
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

該方法用于取消任務。參數的意義是如果任務已經開始,是否嘗試中斷。

/**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     */
    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }

喚醒(unpark方法)所有等待該任務的線程,并從等待列表中移除。最后調用了done方法。該方法在FutureTask為空,主要目的是便于子類定制自己的行為。接著將任務置為null。

再來看看最常用的get方法。

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //此時任務尚未完成,進入到等待中
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        //
        return report(s);
    }

    /**
     * @throws CancellationException {@inheritDoc}
     */
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

    /**
     * 該方法只用于獲取已經正常完成的任務的返回值 其他情況都會拋異常
     * Returns result or throws exception for completed task.
     *
     * @param s completed state value
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

第一個get方法會一直阻塞到任務完成。第二個get方法會至多阻塞指定的時長。來看看兩個get中都調用的一個方法。

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        //計算等待的截止時間點
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        //自旋開始
        for (;;) {
            //如果當前線程被中斷了則移除所有在等待的線程
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            // 如果任務已經結束了 則返回當前狀態
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
           //如果任務在進行中(狀態馬上就會變),則讓出cpu,等待下次cpu時間片,暫時不要time out
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
           //頭一次自旋則創建一個等待節點,繼續自旋
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
               //將當前線程加入到等待隊列中,加入到隊列的頭部
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            //到這里時 當前線程已經加入到等待隊列中了
            else if (timed) {
                //如果是設置了時間限制,則計算到時間了沒,由于前面讓出了CPU時間片,所以有可能再次執行時已經過點了
                nanos = deadline - System.nanoTime();
                //到點后還沒執行完則移除q之后的所有等待線程,并返回當前狀態
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                //掛起當前線程
                LockSupport.parkNanos(this, nanos);
            }
            else
                //掛起當前線程
                LockSupport.park(this);
        }
    }

再來看看核心方法

public void run() {
        // 前面半句是判斷任務的狀態是不是初始狀態,只有初始狀態的任務才能執行run
        // 后面半句是判斷執行該任務的線程是否為空,如果不為空則將當前線程賦值給runner
        // 如果任務不為初始狀態 或者 已經有指定的執行線程了 就直接return,這說明已經有線程在執行該任務了
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            //這里就比較簡單了,直接用指定的線程執行任務
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    //異常的情況下
                    result = null;
                    ran = false; 
                    setException(ex);
                }
                //正常完成情況下 調用set方法
                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);
        }
    }


    protected void setException(Throwable t) {
        //先將任務狀態置為完成中
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //將任務的返回值置為異常對象
            outcome = t;
           //將任務置為異常狀態
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
           //喚醒所有等待線程
            finishCompletion();
        }
    }

    /** 保證所有的強制中斷只下發到正在執行中或者是重置后的任務中
     * Ensures that any interrupt from a possible cancel(true) is only
     * delivered to a task while in run or runAndReset.
     */
    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();
    }

FutureTask還提供了一個可復用自身的方法。我們注意到run方法中會判斷任務是否是初始狀態,如果不是則不予執行。這意味著一個已經完成的任務是不可能再次被執行的。而FutureTask的runAndReset方法則是讓任務實現復用。

protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

可以看到幾乎和run方法一樣,但是不同點在于任務執行完畢后并沒有調用set方法,即并沒有改變任務的狀態,也沒有將任務的執行結果保存在outcome中。方法僅在任務成功執行且為初始狀態時返回true。

最后是該類中的一個內部類

static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

其實就是一個單向鏈表,保存等待中的線程。

FutureTask中最復雜的方法

/**
     * Tries to unlink a timed-out or interrupted wait node to avoid
     * accumulating garbage.  Internal nodes are simply unspliced
     * without CAS since it is harmless if they are traversed anyway
     * by releasers.  To avoid effects of unsplicing from already
     * removed nodes, the list is retraversed in case of an apparent
     * race.  This is slow when there are a lot of nodes, but we don't
     * expect lists to be long enough to outweigh higher-overhead
     * schemes.
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
                    else if (pred != null) {
                        pred.next = s;
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

該方法旨在并發情況下能清除掉所有等待某個FutureTask完成的線程節點。

FutureTask全程沒有加鎖,全部是調用Unsafe類的cas方法來實現的。

總結

FutureTask將原始的任務(Callable或者Runnable)封裝了一層,加入了狀態位,并且自己維護狀態。最終提交到線程池的對象其實是一個FutureTask,由于FutureTask實現了Runnable接口,因此線程池執行的其實是FutureTask的run方法。任務的狀態變更都是FutureTask自己完成的,線程池對于FutureTask內部的狀態一無所知。一個FutureTask在執行前被取消,并不意味著線程池不再派出線程去執行FutureTask,線程池照樣會派出線程去執行該FutureTask,只是在執行FutureTask的run方法時,FutureTask判斷自己已經被取消了,就直接return了,不再執行包在其中的原始任務了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,517評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,087評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,521評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,493評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,207評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,603評論 1 325
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,624評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,813評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,364評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,110評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,305評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,874評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,532評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,953評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,209評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,033評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,268評論 2 375

推薦閱讀更多精彩內容