讀FutureTask源碼


//一個可以異步返回計算的結果
//它同時實現了Future和Runnable
//先看構造函數
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}

//運行runnable並返回給定的result
public FutureTask(Runnable runnable, V result) {
//適配器模式轉化runnable接口
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);
}

//適配器模式轉化runnable接口
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}


public void run() {
//如果state不等於0或者設置當前已經被其他線程佔用了直接返回。
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 = null;
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();
}
}


private void finishCompletion() {
//釋放所有等待線程
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
}


private void handlePossibleCancellationInterrupt(int s) {

if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt

}

protected void done() { }

//獲取結果
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();
//超時刪除q
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;
if (q.thread != null)
pred = q;
//到這裏說明q.thread==null,q是需要刪除的節點。
else if (pred != null) {
//修改上一個節點的next
pred.next = s;
//上一個節點被刪了,重新循環。
if (pred.thread == null)
continue retry;
}
//走到這裏說明第一個節點就是被刪除的節點
else if (!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);
}

//在一定時間內等待獲取結果超時拋出異常
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);
}


//任務是否取消
public boolean isCancelled() {
return state >= CANCELLED;
}

//任務是否完成
public boolean isDone() {
return state != NEW;
}


//試圖取消任務的執行
public boolean cancel(boolean mayInterruptIfRunning) {
//任務已經開始直接返回false
if (state != NEW)
return false;
//試圖中斷
if (mayInterruptIfRunning) {
if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
return false;
Thread t = runner;
if (t != null)
t.interrupt();
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
}
//嘗試取消
else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
return false;
finishCompletion();
return true;
}

//將結果設置爲異常
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}


//執行計算但不設置結果執行完後重置
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable<V> c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} finally {
runner = null;
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章