【java并發編程】全面理解Future模式的原理和使用(Future、RunnableFuture、FutureTask、Callable的理解及源碼分析)

一、前言

????通常,java中創建多線程的兩種方式:

  • 直接繼承Thread;
  • 實現Runnable接口。

????考慮到一些邏輯需要一定的先后順序,如果直接用這兩種方式都會有共同的缺點:

  • 通常為阻塞式(通過join等待一個線程結束,但這樣就失去了多線程的意義),或者通過wait、notify、notifyAll并結合狀態變量等來進行并發設計,設計起來相當復雜;
  • 線程執行完成后難以獲取線程執行結果(需要通過共享變量、線程間通信等方式來獲取, 比較復雜)

????由此,我們想到了多線程開發中常見的Future模式。開發中經常有一些操作可能比較耗時,但又不想阻塞式的等待,這時可以先執行一些其它操作,等其它操作完成后再去獲取耗時操作的結果,這就是Future模式的描述。對應于生活中例子比比皆是:比如,打開電飯煲燒米飯后繼續炒菜,等炒菜完了去看下米飯有沒有煲熟,過程中無需死等電飯煲把飯煲熟,只有在炒完菜后這個時間點,我們才嘗試去看電飯煲煲飯的結果,這就是Future模式的一個生活原型。
????java從1.5開始,在并發包中提供了Future模式的設計,我們這要結合Callable、Future/FutureTask就能很容易的使用Future模式。

二、Future模式的一個簡單示例

???? 我們來看一個簡單示例:

    public static void main(String[] args) throws InterruptedException, ExecutionException
    {
        
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> future = executor.submit(new Callable<Integer>(){

            @Override
            public Integer call()
                throws Exception
            {
                int total = 0;
                for(int i = 5001; i<=10000; i++){
                    total += i;
                }
                return total;
            }
            
        });
        
        System.out.print("Submit future task now...");
        executor.shutdown();
        
        int total = 0;
        for(int i = 1; i<=5000; i++){
            total += i;
        }
        
        total += future.get();
        
        System.out.print("1+2+...+10000 = " + total);
    }

示例中計算了1~10000且步長為1的等比數列之和,將數列拆均分成兩部分分別求和,最后進行累計。Future模式通常需要配合ExecutorService和Callable一起使用,代碼中采用ExecutorService的submit方法提交Callable線程,在主線程任務完成后獲取Callable線程的結果。

三、源碼分析

  1. ????
    我們先直接看下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個方法含義如下:

  • cancel(boolean mayInterruptIfRunning) : 取消任務, 取消成功返回true;入參mayInterruptIfRunning表示是否允許取消正在執行中的任務。
  • isCancelled() : 返回是否取消成功
  • isDone() : 返回任務是否已經完成
  • get() : 返回執行結果,如果任務沒有完成會阻塞到任務完成再返回
  • get(long timeout, TimeUnit unit) 獲取執行結果并設置超時時間,如果超時返回null
  1. ????
    Future模式通常需要配合ExecutorService和Callable一起使用,通過ExecutorService的submit方法提交Callable線程。我們知道,execute()方法在Executor接口中定義,而submit()方法在ExecutorService接口中定義,ExecutorService接口繼承Executor接口:
    public interface Executor {
        void execute(Runnable command);
    }
    
    public interface ExecutorService extends Executor {
        ...
        <T> Future<T> submit(Callable<T> task);
            
        <T> Future<T> submit(Runnable task, T result);
            
        Future<?> submit(Runnable task);
        ...
    }
  1. ????
    ExecutorService只是一個接口,我們以上一節的newCachedThreadPool為例,看下它的源碼:
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  1. ????
    上面結果返回的是一個ThreadPoolExecutor,它是ExecutorService的一個子類,看ThreadPoolExecutor源碼可以發現,ThreadPoolExecutor沒有實現submit方法,它的submit方法由其直接父類AbstractExecutorService實現:
    ...
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
    ...
    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    ...    
    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
    ...
  1. ????
    在上面三個submit方法中,無論是Callable接口還是Runnable接口,均是轉化成了RunnableFuture實例,看下RunnableFuture的實現:
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
  1. ????
    RunnableFuture接口同時繼承了Runnable接口和Future接口。再看下上面講Callable或Runnable轉化成RunnableFuture實例的實現:
    ...
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }
    
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    ...
  1. ????
    通過兩個newTaskFor方法分別將Callable和Runnable實例轉化成FutureTask實例,FutureTask是RunnableFuture的實現,上述源碼中涉及FutureTask的兩種構造函數:
    ...
    private Callable<V> callable;
    private volatile int state;
    private static final int NEW          = 0;
    ...
    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
    }
    ...
  1. ????
    對于Callable實例,直接將入參Callable對象賦值給this.callable屬性,并設置this.state屬性為NEW; 而對于Funnable實例,需要通過Executors類的callable(runnable, result)方法轉化成Callable實例:
    public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
  1. ????
    Executors類的callable(runnable, result)方法實際生成了一個RunnableAdapter對象,看下其源碼:
    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;
        }
    }

????
顯而易見,RunnableAdapter類實現了Callable接口的call()方法,內部調用了Runnable實例的run()方法,并返回預先傳過來的result值。

  1. ????
    回過頭來看下,FutureTask類實現了RunnableFuture接口,進而實現了Runnable接口和Future接口的統一,那么它是如何實現Runnable接口的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);
        }
    }
    
    ...
    
    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
    
    ...
    
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

????
可以看到FutureTask的run()方法內部調用了Runnable實例的call()方法,并且如果運行成功,將call()方法的返回值賦值給outcome,否則將異常賦值給outcome。
????
這樣也就容易理解ExecutorService的submit方法實現中是如何調用execute(Runnable command)方法的了,它將Runnable或者Callable實例統一轉換成了RunnableFuture實例,由于RunnableFuture繼承了Runnable接口,所以線程池可以通過execute(Runnable command)方法來進行處理。

  1. ????回過來看下FutureTask類的get()方法實現:
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return 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);
    }
    
    ...
    
        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);
        }
    }
  • 如果狀態state為任務執行中,則阻塞等待,否則通過report(s)返回結果。返回結果時:如果狀態正常,則直接返回outcome;如果取消或者中斷,則返回CancellationException異常;如果執行異常,則返回ExecutionException。
  • 上述源碼可以看出,get()方法通過awaitDone方法進行阻塞等待,awaitDone方法實現上采用LockSupport.park()進行線程阻塞,在FutureTasl的run()方法執行完成或異常發生,會執行set(V v)方法或setException(Throwable t)方法,兩者的實現中都會調用finishCompletion()方法,并在finishCompletion()方法中采用LockSupport.unpark方法進行了線程喚醒:
    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
    }

四、總結

????通過上述舉例和源碼分析我們理解了java中Future模式的原理和使用,Future模式對于一些耗時操作(比如網絡請求等)的性能提升還是比較有用的,實際開發中可以靈活運用。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容