FutureTask
提前加載稍後需要的數據
Future表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並獲取計算的結果。計算完成後只能使用 get 方法來獲取結果,如有必要,計算完成前可以阻塞此方法。
Callable返回結果並且可能拋出異常的任務。實現者定義了一個不帶任何參數的叫做 call 的方法。
/**
* The run state of this task, initially NEW. The run state
* transitions to a terminal state only in methods set,
* setException, and cancel. During completion, state may take on
* transient values of COMPLETING (while outcome is being set) or
* INTERRUPTING (only while interrupting the runner to satisfy a
* cancel(true)). Transitions from these intermediate to final
* states use cheaper ordered/lazy writes because values are unique
* and cannot be further modified.
*
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
private volatile int state;
//表示是個新的任務或者還沒被執行完的任務。這是初始狀態。
private static final int NEW = 0;
//任務已經執行完成或者執行任務的時候發生異常,但是任務執行結果或者異常原因還沒有保存到outcome字段
// (outcome字段用來保存任務執行結果,如果發生異常,則用來保存異常原因)的時候,
// 狀態會從NEW變更到COMPLETING。但是這個狀態會時間會比較短,屬於中間狀態。
private static final int COMPLETING = 1;
//任務已經執行完成並且任務執行結果已經保存到outcome字段,狀態會從COMPLETING轉換到NORMAL。這是一個最終態。
private static final int NORMAL = 2;
//任務執行發生異常並且異常原因已經保存到outcome字段中後,狀態會從COMPLETING轉換到EXCEPTIONAL。這是一個最終態。
private static final int EXCEPTIONAL = 3;
//任務還沒開始執行或者已經開始執行但是還沒有執行完成的時候,用戶調用了cancel(false)方法取消任務且不中斷任務執行線程,
// 這個時候狀態會從NEW轉化爲CANCELLED狀態。這是一個最終態。
private static final int CANCELLED = 4;
//任務還沒開始執行或者已經執行但是還沒有執行完成的時候,
// 用戶調用了cancel(true)方法取消任務並且要中斷任務執行線程但是還沒有中斷任務執行線程之前,
// 狀態會從NEW轉化爲INTERRUPTING。這是一箇中間狀態。
private static final int INTERRUPTING = 5;
//調用interrupt()中斷任務執行線程之後狀態會從INTERRUPTING轉換到INTERRUPTED。這是一個最終態。
private static final int INTERRUPTED = 6;
構造
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
//設置回調函數,返回value
this.callable = callable;
//初始狀態
this.state = NEW; // ensure visibility of callable
}
帶返回構造
public FutureTask(Runnable runnable, V result) {
//任務執行成果,返回result
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of 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;
//適配器,底層包裝task
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
//返回設置結果
return result;
}
}
run
因爲繼承了runnable接口,所以使用線程時,直接調用run
public void run() {
//當前狀態不是新建,說明已經執行過或者取消了,直接返回
if (state != NEW ||
// 狀態爲新建,則嘗試添加當前線程到runner中,如果失敗直接返回
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
//回調函數有值且狀態新建
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//調用回調函數,保存值到result中
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 setException(Throwable t) {
//將當前狀態 NEW => COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//異常保存到outcome中
outcome = t;
//將當前狀態COMPLETING => EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
protected void set(V v) {
// NEW => COMPLETING
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
// outcome保存返回結果
outcome = v;
//COMPLETING => NORMAL
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
get
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();
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);
}
}
private void removeWaiter(WaitNode node) {
if (node != null) {
//清空當前線程
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
// pred => q => s
if (q.thread != null)
pred = q;
else if (pred != null) {
//刪除中間thread爲null的數據
//當q.thread=null且,pred不爲null,則刪除q節點
pred.next = s;
if (pred.thread == null) // check for race
continue retry;
}
else if (!
//刪除waiters節點的頭數據,並更新爲waiters.next
//當q.thread=null且,pred爲null,則替換爲s節點,如果q爲waiters節點,且修改失敗,則跳過當前循環,繼續執行下一個循環
UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
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);
}
cancel
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(
//如果任務已經結束
state == NEW &&
//且將 NEW => mayInterruptIfRunning需要中斷則設置爲 INTERRUPTING 否則 CANCELLED
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
//修改狀態爲INTERRUPTED
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
finishCompletion
private void finishCompletion() {
//成功,異常,中斷的時候會調用
// assert state > COMPLETING;
//依次遍歷waiters鏈表,喚醒節點中的線程,然後把callable置空。
for (WaitNode q; (q = waiters) != null;) {
//清空waiters
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更新爲下一個節點
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
總結
每次涉及到成功,異常,中斷的時候會喚醒所有等待的線程
最後執行的會先添加到等待線程頭節點中.也就是最先喚醒的時最後執行的線程
內部維護7個狀態,分別監控執行,取消,中斷3個執行過程.