FutureTask的是實(shí)現(xiàn)類圖如下:
Screenshot - 2016年12月01日 - 14時(shí)08分12秒.png
它的實(shí)現(xiàn)也比較簡(jiǎn)單,主要是用了UNSAFE類來(lái)實(shí)現(xiàn)大部分的功能。
它的屬性主要有state(表示狀態(tài)),callable(FutureTask指向的要運(yùn)行的callable對(duì)象),outcome(Object對(duì)象,運(yùn)行結(jié)果,可能是異常), runner(Thread對(duì)象 線程),waiters(WaitNode對(duì)象,它是鏈表元素,表示等待結(jié)果的線程)
它的許多操作都是以狀態(tài)驅(qū)動(dòng)的,通過(guò)CAS改變狀態(tài)成功后進(jìn)行后續(xù)操作:
下面兩個(gè)方法在類中其他方法中會(huì)用到如run()方法中運(yùn)行成功后設(shè)置結(jié)果值
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon successful completion of the computation.
*
* @param v the value
*/
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
/**
* Causes this future to report an {@link ExecutionException}
* with the given throwable as its cause, unless this future has
* already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon failure of the computation.
*
* @param t the cause of failure
*/
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
FutureTask的大部分方法比較簡(jiǎn)單,重點(diǎn)是一下幾個(gè):
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//置狀態(tài)成功后
if (mayInterruptIfRunning) {//是否使用中斷線程
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();//取消線程運(yùn)行后的后續(xù)操作
}
return true;
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {//喚醒等待結(jié)果的線程
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {//原子替換waiters變量為空
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();//這個(gè)方法為空,子類可以實(shí)現(xiàn)它增加額外的的操作
callable = null; // to reduce footprint
}
第二個(gè)獲取結(jié)果方法
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)//判斷狀態(tài),然后等待,也會(huì)判斷等待后返回的結(jié)果狀態(tài)
throw new TimeoutException();
return report(s);//使用report方法發(fā)會(huì)結(jié)果
}
這個(gè)方法就是無(wú)限循環(huán),每次循環(huán)只做滿足條件的一件事
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) {//狀態(tài)已經(jīng)表示結(jié)束了
if (q != null)
q.thread = null;//把q的線程之空,它是當(dāng)前線程,表示當(dāng)前線程已經(jīng)不等待了,不必在其他的方法中喚醒了,q也沒(méi)從隊(duì)列移除,主要減少移除隊(duì)列的次數(shù),提高性能
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();//生成等待者,詳見(jiàn)相應(yīng)類,很簡(jiǎn)單
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);//加入等待隊(duì)列
else if (timed) {//等待一段時(shí)間
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) {//一直到末尾才結(jié)束
s = q.next;
if (q.thread != null)//不是需要移除的節(jié)點(diǎn),則增加個(gè)前節(jié)點(diǎn)
pred = q;
else if (pred != null) {//q現(xiàn)在是移除節(jié)點(diǎn),但是前節(jié)點(diǎn)不為空,直接改鏈表結(jié)構(gòu)
pred.next = s;
if (pred.thread == null) // check for race//前置節(jié)點(diǎn)的線程為空,則從頭再來(lái)一次
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))//并發(fā)修改了首節(jié)點(diǎn),失敗則從頭再來(lái)
continue retry;
}
break;
}
}
}
//以當(dāng)前線程來(lái)運(yùn)行
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))//置runner為當(dāng)前線程
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);
}
}