戳藍字「TopCoder」關注咱們哦!node
編者注:FutureTask用於在異步操做場景中,FutureTask做爲生產者(執行FutureTask的線程)和消費者(獲取FutureTask結果的線程)的橋樑,若是生產者先生產出了數據,那麼消費者get時能會直接拿到結果;若是生產者還未產生數據,那麼get時會一直阻塞或者超時阻塞,一直到生產者產生數據喚醒阻塞的消費者爲止。話很少說,下來開始FutureTask的分析~web
Future接口和實現Future接口的FutureTask,表明異步計算的結果,Future使用示例以下:安全
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10,
60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
Future future = executor.submit(() -> {
System.out.println("hello world");
return "hello world";
});
System.out.println(future.get());
Future接口聲明以下:微信
FutureTask除了實現Future接口外,還實現了Runnable接口。所以,FutureTask能夠交給Executor執行,也能夠由調用線程直接執行(FutureTask.run())。根據FutureTask.run()方法被執行的時機,FutureTask能夠處於如下3種狀態:未啓動、運行中、已完成。app
當FutureTask處於未啓動或已啓動狀態時,執行FutureTask.get()方法將致使調用線程阻塞;當FutureTask處於已完成狀態時,執行FutureTask.get()方法將致使調用線程當即返回結果或拋出異常。異步
當FutureTask處於未啓動狀態時,執行FutureTask.cancel()方法將致使此任務永遠不會被執行;this
當FutureTask處於已啓動狀態時,執行FutureTask.cancel(true)方法將以中斷執行此任務線程的方式來試圖中止任務;spa
當FutureTask處於已啓動狀態時,執行FutureTask.cancel(false)方法將不會對正在執行此任務的線程產生影響(讓正在執行的任務運行完成);.net
當FutureTask處於已完成狀態時,執行FutureTask.cancel(…)方法將返回false。線程
FutureTask的生命週期以下:
Future.get() 阻塞/喚醒原理
執行future.get()時,若是對應線程還未執行完,則會阻塞當前線程,以FutureTask爲例,FutureTask中有一個int型的狀態標誌,表示future對應線程的運行狀態。
/**
* 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.get()時,若是Future對應的任務已完成(正常執行完成或者拋出異常),執行返回;若是Future對應的任務未執行完成,則會將當前線程封裝成一個NodeWait,以CAS方式添加到FutureTask.waiters
鏈表上(單向鏈表,新節點都會做爲head node添加上),而後會阻塞當前線程(包括超時阻塞)。
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING) // 線程未執行完成
s = awaitDone(false, 0L);
return report(s);
}
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(); // future task已完成,正在賦值outcome,get()返回的值就是outcome,這時不用加入WaitNode便可
else if (q == null)
q = new WaitNode(); // 生成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);
}
}
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); // 拋出異常
}
在任務執行(run()方法)中,調用result = callable.call
方法,正常執行完畢後調用set(result)設置Future結果;出現異常則調用setException(ex)。最後會調用finishCompletion()來喚醒阻塞在Future的全部線程。
設置完數據以後(無論是正常數據仍是對應異常),當等待數據的線程來get
時,就會返回或者直接給它拋異常;若是當線程已經get過並阻塞在這裏時,FutureTask須要將這些線程喚醒起來。
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();
}
}
// 喚醒全部等待線程
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中的waiters是一個單向鏈表,若是多個線程阻塞在該Future上,最新阻塞的線程排列在鏈表前面,喚醒線程時依次從前到後遍歷鏈表喚醒線程,這樣處理貌似對最開始阻塞在Future上的線程不太公平哈,由於最開始阻塞的線程是到最後才被喚醒的。
推薦閱讀
本文分享自微信公衆號 - TopCoder(gh_12e4a74a5c9c)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。