Future接口和Callable接口以及FeatureTask詳解


類繼承關系

Callable接口

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

Callable接口中只有一個call()方法,和Runnable相比,該方法有返回值並允許拋出異常。
但是這里有一個問題,進程是要通過Thread類去創建的,但是Thread的target必須是實現了Runnable接口的類對象,所以Callable對象無法直接作為Thread對象的接口;所以要想作為target,必須同時實現Runnable接口。
Java提供了一個FutureTask類,該類實現了Runnable接口,該類的run()方法會調用Callable對象的call()方法,這樣就能把Callable和Thread結合起來使用了。同時為了方便對Callable對象的操作,Java還提供了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;
}

FutureTask類

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

public class FutureTask<V> implements RunnableFuture<V> {
...
}

FutureTask是Runnable, Future接口的實現類。
下面看下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;

FutureTask中定義了上述幾種狀態。

成員變量

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

構造函數

   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 callable)

這個構造方法比較簡單,傳入一個Callable對象。

FutureTask(Runnable runnable, V 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);
    }

這里只是創建RunnableAdapter對象,再看下RunnableAdapter類(是Executors的內部類):

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也是實現了Runnable接口,並通過call()方法調用最開始傳入的Runnable對象的run()方法,並且返回最開始傳入的result值。
這里實際上是將一個Runnable對象偽裝成一個Callable對象,是適配器模式。

關鍵的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);
        }
    }

sun.misc.Unsafe是個什么東東?可以參考這里這里

UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread())

這行代碼是什么含義呢?compareAndSwapObject可以通過反射,根據偏移量去修改對象,第一個參數表示要修改的對象,第二個表示偏移量,第三個參數用於和偏移量對應的值進行比較,第四個參數表示如果偏移量對應的值和第三個參數一樣時要把偏移量設置成的值。翻譯成人話就是:如果this對象的runnerOffset偏移地址的值為null,就把它設置為Thread.currentThread()。
那再來看看runnerOffset是啥:

runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));

對應的就是runner成員變量。
也就是說如果狀態不是NEW或者runner不是null,run方法就直接返回。
try塊中的方法就比較好理解了,就是調Callable對象的call()方法,並通過set方法設置result。

get方法

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

get方法主要是調用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根據當前狀態直接返回或阻塞等待,代碼流程不分析,主要看下幾個關鍵的點。

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

WaitNode就是一個鏈表結構,用於記錄等待當前FutureTask結果的線程。
注意,上面調用的LockSupport.park(this)和LockSupport.parkNanos(this, nanos)方法,LockSupport類是Java 6中引入的,提供了基本的線程同步原語,前面的兩個調用會導致調用線程進入阻塞,直到run()方法中調用set(result)或者setException(ex)。
看看set()方法:

    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

先設置state,並將結果賦給outcome,然后更新state的最終狀態,接着調用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
    }

finishCompletion()的作用就是根據waiters鏈表,挨個喚醒等待FutureTask執行結果的線程,喚醒操作是通過LockSupport.unpark(t)實現的。

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;
    }

cancle()就是根據是否可中斷來設置state及中斷狀態。

參考文檔

JDK源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM