FutureTask相關

Nooooone發表於2021-07-04
  • 上週因為專案中的執行緒池引數設定的不合理,引發了一些問題,看了下程式碼,發現對JUC中的一些概念需要再清晰些。

Runnable

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
  • Runable是一個interface,定義了run()方法,The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread。如果想在其他執行緒中執行你的task,需要實現這個介面。

Callable

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
  • 有了Runnable,為啥還需要Callable呢,可以看到Runnable和Callable的兩個不同,第一,Runnable是沒有返回值的,第二,Runnable是不會丟擲checked exception的,而有時候我們需要知道任務執行之後的返回,同時也希望利用異常機制完成一些邏輯。所以有了Callable。
  • JUC中的Executors這個Factory類,提供了Runnable轉Callable的方法。

Future

  • future 是一個inteface,提供了一系列方法,來幫助我們獲取非同步執行的task的執行狀況和執行結果。

FutureTask

  • FutureTask實現了RunnableFuture介面,即既實現了Runnable介面,又實現了Future介面。所以他有兩個功能,第一,作為一個task,提交到別的執行緒中非同步執行,第二,通過future提供的一些介面,獲取task的非同步執行狀態。
/**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * 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 */
    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;
  • 看下FutureTask的幾個屬性,首先state表示當前task的執行狀態,其中,開始狀態位NEW表示task還沒開始執行。NORMAL,CANCELLED,INTERRUPTED為終態,COMPLETING和INTERRUPTING為臨時狀態,最終會通過上面的幾個狀態轉移路徑,轉移到終態。
  • callable,表示具體執行的任務。
  • outcome, task 執行的返回結果
  • runner,執行這個task的執行緒
  • waiters,通過get方法獲取此task執行結果被阻塞的執行緒。
  • 看下幾個核心的方法,我們知道,futuretask提交到別的執行緒裡後,最終會呼叫task的run方法執行具體邏輯。
public void run() {
        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);
                }
                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);
        }
    }
  • run方法執行時,首先檢查當前的狀態是否是NEW,如果不是NEW說明已經被執行過了。開始執行之前,標記執行當前task的執行緒到runner。
  • 呼叫callable的run方法,執行。拋異常時,設定setException。正常結束時,set結果。看下這兩步裡都會調到的finishCompletion方法。
/**
     * 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
    }
  • 這裡主要是在通知所有阻塞在watch這個task結果的執行緒,通知他們當前task已經執行結束了。
  • 在執行結束時,看到finally裡還有段邏輯
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);
        }

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();
    }
  • 這是在幹嘛呢,是因為,即使我們在上一步通過set或者setException設定了當前task的狀態,但可能有別的執行緒在通過呼叫cancel來設定當前task的狀態,如果有的話,這裡就自旋空轉,直到cancel方法執行結束。
  • 那cancel方法是怎麼工作的呢
public boolean cancel(boolean mayInterruptIfRunning) {
        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;
    }
  • cancel方法其實就是通過找到執行當前task的runner,然後呼叫thread的interrupt方法,這裡需要注意的是,thread.interrupt方法僅僅是設定一個標誌位,具體執行緒有沒有響應,要看自己的實現。反正這裡就是調一把interrupt然後就走了,然後通知所有watch的執行緒。
  • watch的執行緒,通過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;
            }
            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) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
    }
  • 核心邏輯就是,先把自己這個執行緒放到watch的waitNodes棧中,然後park 等待,直到task的狀態>COMPLETING.

reference