FutureTask被設計爲一個可刪除的異步計算任務,實現了RunnableFuture接口,提供了一系列方法來啓動、刪除任務、查詢當前的計算狀態,以及取回計算結果。要取回結果只能等到任務完成,由於取回結果的方法get(..)是一個阻塞方法,計算沒結束時會一直等到結束,或超時、或中斷。java
FutureTask能夠包裝Callable或Runnable對象,而後能夠提交給Executors來執行。算法
FutureTask提供了protected方法好比done(), 用戶可在這些方法中定製任務。安全
run(), 是在Task線程(而非下發任務的線程)裏運行的, c.call()是核心業務方法(所謂的計算)併發
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); } }
計算結束後調用set設置結果:異步
protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
sdk5開始,concurrent包中的併發處理大量使用了CAS, 這裏set方法也用CAS來改變任務執行的狀態(注意當前代碼是在Task線程裏執行的),stateOffset是當前任務的狀態標誌state在FutureTask對象中的偏移量。this
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; ... // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long stateOffset; private static final long runnerOffset; private static final long waitersOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = FutureTask.class; stateOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("state")); runnerOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("runner")); waitersOffset = UNSAFE.objectFieldOffset (k.getDeclaredField("waiters")); } catch (Exception e) { throw new Error(e); } }
任務完成後會釋放等待結果的線程(通常是下發任務的線程),finishCompletion()是Treiber算法的實現,它的做用就是實現一個線程安全的非阻塞式的棧 。 那麼這些阻塞的線程哪裏來的呢? 前面說過,取得結果的get方法是個阻塞方法,若是在計算有結果前調用會致使等待。spa
/** * 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 }
get方法能夠設置超時時間。從其調用的awaitDone方法能夠看出,若是尚未計算結果的話, 等待結果的線程,即調用get方法的線程(通常是下發任務的線程)會經過LockSuppport類掛起。 這裏也用到了CAS, 有CAS的場景通常就會出現while(true) 或 for(;;)這樣的循環 ==!。 到這裏,回頭看一下前面的finishCompletion()方法,整個流程基本就清楚了。線程
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); } /** * 等待結果完成、或者被意外中斷、或者等待超時. * * @param timed true if use timed waits * @param nanos time to wait, if timed * @return state upon completion */ 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); } }