Java併發編程:Callable、Future和FutureTask原理解析

返回結果的任務Callable與Future

Executor框架使用Runnable做爲其基本的任務表示形式。Runnable是一種有很大侷限的抽象,它不能返回一個值或拋出一個受檢查的異常。Runnable接口:html

public interface Runnable {
    public abstract void run();
}
  • 因爲run()方法返回值爲void類型,因此在執行完任務以後沒法返回任何結果。

許多任務實際上都是存在延遲的計算,對於這些任務,Callable是一種更好的抽象:它會返回一個值,並可能拋出一個異常。Callable接口:git

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;
}
  • 能夠看到,這是一個泛型接口,call()函數返回的類型就是傳遞進來的V類型。

Runnable和Callable描述的都是抽象的計算任務。這些任務一般是有生命週期的。Executor執行的任務有4個生命週期階段:建立、提交、開始和完成。因爲有些任務可能要執行很長時間,所以一般但願能夠取消這些任務。在Executor框架中,已提交但還沒有開始的任務能夠取消,對於已經開始執行的任務,只有當它們響應中斷時才能取消。github

Future表示一個任務的生命週期,並提供了方法來判斷是否已經完成或取消,以及獲取任務的結果和取消任務等。Future接口:算法

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
  • 在Future接口中聲明瞭5個方法,下面依次解釋每一個方法的做用:
  1. cancel方法用來取消任務,若是取消任務成功則返回true,若是取消任務失敗則返回false。參數mayInterruptIfRunning表示是否容許取消正在執行卻沒有執行完畢的任務,若是設置true,則表示能夠取消正在執行過程當中的任務。若是任務已經完成,則不管mayInterruptIfRunning爲true仍是false,此方法確定返回false,即若是取消已經完成的任務會返回false;若是任務正在執行,若mayInterruptIfRunning設置爲true,則返回true,若mayInterruptIfRunning設置爲false,則返回false;若是任務尚未執行,則不管mayInterruptIfRunning爲true仍是false,確定返回true。數據結構

  2. isCancelled方法表示任務是否被取消成功,若是在任務正常完成前被取消成功,則返回 true。併發

  3. isDone方法表示任務是否已經完成,若任務完成,則返回true;框架

  4. get()方法用來獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回;異步

  5. get(long timeout, TimeUnit unit)用來獲取執行結果,若是在指定時間內,還沒獲取到結果,就直接返回null。函數

也就是說實際上Future提供了三種功能:ui

  1. 判斷任務是否完成;
  2. 中斷任務;
  3. 獲取任務執行結果。

Future與Callable的關係與ExecutorService與Executor的關係對應。

FutureTask

Future只是一個接口,沒法直接建立對象,所以有了FutureTask。 
咱們先來看下FutureTask的實現:

public class FutureTask<V> implements RunnableFuture<V>
  • FutureTask類實現了RunnableFuture接口:
public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}
  • RunnableFuture繼承了Runnable和Future接口,而FutureTask實現了RunnableFuture接口。

FutureTask的繼承關係和方法如圖所示: 
FutureTask

FutureTask是一個可取消的異步計算,FutureTask 實現了Future的基本方法,提供start cancel 操做,能夠查詢計算是否已經完成,而且能夠獲取計算的結果。結果只能夠在計算完成以後獲取,get方法會阻塞當計算沒有完成的時候,一旦計算已經完成, 那麼計算就不能再次啓動或是取消。

一個FutureTask 能夠用來包裝一個 Callable 或是一個Runnable對象。由於FurtureTask實現了Runnable方法,因此一個 FutureTask能夠提交(submit)給一個Excutor執行(excution). 它同時實現了Callable, 因此也能夠做爲Future獲得Callable的返回值。

FutureTask有兩個很重要的屬性分別是state和runner, FutureTask之因此支持canacel操做,也是由於這兩個屬性。 
其中state爲枚舉值:

private volatile int state; // 注意volatile關鍵字
    /**
     * 在構建FutureTask時設置,同時也表示內部成員callable已成功賦值,
     * 一直到worker thread完成FutureTask中的run();
     */
    private static final int NEW = 0;

    /**
     * woker thread在處理task時設定的中間狀態,處於該狀態時,
     * 說明worker thread正準備設置result.
     */
    private static final int COMPLETING = 1;

    /**
     * 當設置result結果完成後,FutureTask處於該狀態,表明過程結果,
     * 該狀態爲最終狀態final state,(正確完成的最終狀態)
     */
    private static final int NORMAL = 2;

    /**
     * 同上,只不過task執行過程出現異常,此時結果設值爲exception,
     * 也是final state
     */
    private static final int EXCEPTIONAL = 3;

    /**
     * final state, 代表task被cancel(task尚未執行就被cancel的狀態).
     */
    private static final int CANCELLED = 4;

    /**
     * 中間狀態,task運行過程當中被interrupt時,設置的中間狀態
     */
    private static final int INTERRUPTING = 5;

    /**
     * final state, 中斷完畢的最終狀態,幾種狀況,下面具體分析
     */
    private static final int INTERRUPTED = 6;
  • state初始化爲NEW。只有在set, setException和cancel方法中state才能夠轉變爲終態。在任務完成期間,state的值可能爲COMPLETING或INTERRUPTING。 

state有四種可能的狀態轉換:

  • NEW -> COMPLETING -> NORMAL
  • NEW -> COMPLETING -> EXCEPTIONAL
  • NEW -> CANCELLED
  • NEW -> INTERRUPTING -> INTERRUPTED

其餘成員變量:

/** The underlying callable; nulled out after running */
    private Callable<V> callable;   // 具體run運行時會調用其方法call(),並得到結果,結果時置爲null.

    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes   不必爲votaile,由於其是伴隨state 進行讀寫,而state是FutureTask的主導因素。

    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;   //具體的worker thread.

    /** Treiber stack of waiting threads */  
    private volatile WaitNode waiters;     //Treiber stack 併發stack數據結構,用於存放阻塞在該futuretask#get方法的線程。

下面分析下Task的狀態變化,也就一個任務的生命週期: 
建立一個FutureTask首先調用構造方法:

public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
 }
  • 此時將state設置爲初始態NEW。這裏注意Runnable是怎樣轉換爲Callable的,看下this.callable = Executors.callable(runnable, result); 調用Executors.callable:
public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
}
  •  
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;
        }
}
  • 其實就是經過Callable的call方法調用Runnable的run方法,把傳入的 T result 做爲callable的返回結果;

當建立完一個Task一般會提交給Executors來執行,固然也可使用Thread來執行,Thread的start()方法會調用Task的run()方法。看下FutureTask的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);
        }
    }
  • 首先判斷任務的狀態,若是任務狀態不是new,說明任務狀態已經改變(說明他已經走了上面4種可能變化的一種,好比caller調用了cancel,此時狀態爲Interrupting, 也說明了上面的cancel方法,task沒運行時,就interrupt, task得不到運行,老是返回);

若是狀態是new, 判斷runner是否爲null, 若是爲null, 則把當前執行任務的線程賦值給runner,若是runner不爲null, 說明已經有線程在執行,返回。此處使用cas來賦值worker thread是保證多個線程同時提交同一個FutureTask時,確保該FutureTask的run只被調用一次, 若是想運行屢次,使用runAndReset()方法。

這裏

!UNSAFE.compareAndSwapObject(this, runnerOffset,                                   null, Thread.currentThread())
  • 語義至關於
if (this.runner == null ){
    this.runner = Thread.currentThread();
}

接着開始執行任務,若是要執行的任務不爲空,而且state爲New就執行,能夠看到這裏調用了Callable的call方法。若是執行成功則set結果,若是出現異常則setException。最後把runner設爲null。

接着看下set方法:

protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
  • 若是如今的狀態是NEW就把狀態設置成COMPLETING,而後設置成NORMAL。這個執行流程的狀態變化就是: NEW->COMPLETING->NORMAL。

最後執行finishCompletion()方法:

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
 }

接下來分析FutureTask很是重要的get方法:

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
  • 首先判斷FutureTask的狀態是否爲完成狀態,若是是完成狀態,說明已經執行過set或setException方法,返回report(s):
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);
    }
  • 能夠看到,若是FutureTask的狀態是NORMAL, 即正確執行了set方法,get方法直接返回處理的結果, 若是是取消狀態,即執行了setException,則拋出CancellationException異常。

若是get時,FutureTask的狀態爲未完成狀態,則調用awaitDone方法進行阻塞。awaitDone():

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);
        }
    }
  • awaitDone方法能夠當作是不斷輪詢查看FutureTask的狀態。在get阻塞期間:
  • 若是執行get的線程被中斷,則移除FutureTask的全部阻塞隊列中的線程(waiters),並拋出中斷異常;

  • 若是FutureTask的狀態轉換爲完成狀態(正常完成或取消),則返回完成狀態;

  • 若是FutureTask的狀態變爲COMPLETING, 則說明正在set結果,此時讓線程等一等;

  • 若是FutureTask的狀態爲初始態NEW,則將當前線程加入到FutureTask的阻塞線程中去;

  • 若是get方法沒有設置超時時間,則阻塞當前調用get線程;若是設置了超時時間,則判斷是否達到超時時間,若是到達,則移除FutureTask的全部阻塞列隊中的線程,並返回此時FutureTask的狀態,若是未到達時間,則在剩下的時間內繼續阻塞當前線程。

注:本文源碼基於JDK1.7。(1.6經過AQS實現)

相關文章
相關標籤/搜索