主要的實現FutureTask
# FutureTask實際上運行仍是一個runnable,它對callable作了一個封裝,讓開發人員能夠從其中獲取返回值;
FutrueTask是有狀態的 共7種狀態,四種狀態變換的可能
NEW -> COMPLETING -> EXCEPTIONAL
NEW -> CANCELLED
NEW -> COMPLETING -> NORMAL
NEW -> INTERRUPTING -> INTERRUPTED
Callable和runnable的區別
0. 經過call方法調用;
1. 有返回值
2. 能夠拋異常
get結果的實現原理
1. 判斷狀態;
2. 非NEW,COMPLETING狀態則直接 進入report返回結果;
3. 處於NEW,COMPLETING狀態,則進入等待awaitDone();
3.x awaitDone 流程
3.1. 獲取等待的超時時間deadline;
3.2. 進入自旋
3.3. 判斷線程是否被中斷:若是被中斷則移出等待waiters隊列;並拋出異常;
3.4. 判斷FutrueTask狀態:若是">COMPLETING",表明執行完成,進入report;
3.5. 判斷FutrueTask狀態:若是"=COMPLETING",讓出CPU執行Thread.yield();
3.6. 爲當前線程建立一個node節點;
3.7. 將當前線程WaitNode加入等待隊列waiters中;
3.8. 判斷是否超時;
3.9. 經過LockSupport.park掛起線程,等待運行許可;
4. report返回執行結果:若是一切正常就返回執行結果,不然返回Exception;
run具體執行原理以下:
1. 判斷狀態是否正常,避免重複執行;
2. 調用callable的call()方法;
3. 修改執行狀態;保存執行結果;並通知正在等待get的線程;
## 3.x通知機制finishCompletion
3.1. 獲取全部waiters的集合;
3.2. 經過cas 拿到執行權;
3.3. 循環遍歷全部等待的線程,經過LockSupport.unpark 喚醒其執行;
Callable和Future的實現原理(JDK8源碼分析)
1. cancel 取消執行
public boolean cancel(boolean mayInterruptIfRunning) {
// 判斷狀態:只有剛建立的狀況下才能取消
// mayInterruptIfRunning:是否中斷當前正在運行這個FutureTask的線程;
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
// 若是要中斷當前線程,則對runner發佈interrupt信號;
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
// 修改狀態爲:已經通知線程進行中斷
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
// 通知其餘在等待結果的線程
finishCompletion();
}
return true;
}
2. run
public void run() {
// 判斷狀態及設置futuretask歸屬的線程
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 {
// 執行Callable
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;
// 若是狀態爲準備發起中斷信號或者已經發出中斷信號,則讓出CPU(Thread.yield())
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
3. get
public V get() throws InterruptedException, ExecutionException {
int s = state;
// 若是還沒執行完,則等待
if (s <= COMPLETING)
s = awaitDone(false, 0L);
// 經過report取結果
return report(s);
}
3.1 report 取執行結果
private V report(int s) throws ExecutionException {
Object x = outcome;
// 若是一切正常,則返回x(x是callable執行的結果outcome)
if (s == NORMAL)
return (V)x;
// 若是被取消,則拋出已取消異常
if (s >= CANCELLED)
throw new CancellationException();
// 不然拋出執行異常
throw new ExecutionException((Throwable)x);
}
3.2 awaitDone 等待FutureTask執行結束
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
// 記錄等待超時的時間
final long deadline = timed ? System.nanoTime() + nanos : 0L;
// 多個在等待結果的線程,經過一個鏈表進行保存,waitNode就是每一個線程在鏈表中的節點;
WaitNode q = null;
boolean queued = false;
// 死循環...也能夠說是自旋鎖同步
for (;;) {
// 判斷當前這個調用get的線程是否被中斷
if (Thread.interrupted()) {
// 將當前線程移出隊列
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
// 若是狀態非初創或執行完畢了,則跳出循環,經過report()取執行結果
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
// 若是狀態等於已執行,讓出CPU執行,等待狀態變爲正常結束
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
// 若是當前線程尚未建立對象的waitNode節點,則建立一個
else if (q == null)
q = new WaitNode();
// 若是當前線程對應的waitNode尚未加入到等待鏈表中,則加入進去;
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
// 若是有設置等待超時時間,則經過parkNanos掛起當前線程,等待繼續執行的信號
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
// 經過park掛起當前線程,等待task執行結束後給它發一個繼續執行的信號(unpark)
else
LockSupport.park(this);
}
}
4. 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;
// unpark,發佈一個讓它繼續執行的「許可」
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
}