Java并發包FutureTask詳解
我們已經知道了所有提交給jdk線程池的任務都會被封裝成一個FutureTask對象。線程池執行的其實是FutureTask中的run方法。
類圖
可以看到FutureTask實現了Future和Runnable兩個接口,說明它既可以當做任務提交給線程池,也可作為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;
這是用于定義任務狀態的變量。
- 0-初始
- 1-執行中
- 2-已完成
- 3-異常
- 4-已取消
- 5-中斷中
- 6-被中斷
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
- callable-就是我們傳遞進來的原始的任務
- outcome-任務執行的結果
- runner-執行該任務的線程
- waiters-等待任務完成的線程
構造函數
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
FutureTask一共有兩個構造函數,第一個構造函數接收一個Callable對象,第二個構造函數接收一個Runnable對象和一個泛型對象result,這個構造函數中調用Executors的callable方法將Runnable對象包裝成一個Callable對象。
Executors的callable方法核心如下:
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;
}
}
這是將Runnable轉化為Callable對象的過程,其實很簡單,由于Runnable并沒有返回值,而Callable需要返回值,因此就直接拿我們傳遞的result作為返回值了。
注意到,構造函數中將任務的狀態置為NEW。
成員函數
public boolean isCancelled() {
return state >= CANCELLED;
}
public boolean isDone() {
return state != NEW;
}
第一個方法判斷任務是否已經被取消了。可以看到4,5,6狀態均視為已取消。
第二個方法判斷任務是否已經完成。只要不是初始狀態都視為已完成。
public boolean cancel(boolean mayInterruptIfRunning) {
//如果state==NEW,說明任務還沒開始,此時只需要根據傳遞的參數將其狀態置為中斷中或者已取消即可
if (!(state == NEW &&
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
//將狀態置為已中斷
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
該方法用于取消任務。參數的意義是如果任務已經開始,是否嘗試中斷。
/**
* Removes and signals all waiting threads, invokes done(), and
* nulls out callable.
*/
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
}
喚醒(unpark方法)所有等待該任務的線程,并從等待列表中移除。最后調用了done方法。該方法在FutureTask為空,主要目的是便于子類定制自己的行為。接著將任務置為null。
再來看看最常用的get方法。
public V get() throws InterruptedException, ExecutionException {
int s = state;
//此時任務尚未完成,進入到等待中
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//
return report(s);
}
/**
* @throws CancellationException {@inheritDoc}
*/
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);
}
/**
* 該方法只用于獲取已經正常完成的任務的返回值 其他情況都會拋異常
* Returns result or throws exception for completed task.
*
* @param s completed state value
*/
@SuppressWarnings("unchecked")
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);
}
第一個get方法會一直阻塞到任務完成。第二個get方法會至多阻塞指定的時長。來看看兩個get中都調用的一個方法。
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;
}
//如果任務在進行中(狀態馬上就會變),則讓出cpu,等待下次cpu時間片,暫時不要time out
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) {
//如果是設置了時間限制,則計算到時間了沒,由于前面讓出了CPU時間片,所以有可能再次執行時已經過點了
nanos = deadline - System.nanoTime();
//到點后還沒執行完則移除q之后的所有等待線程,并返回當前狀態
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
//掛起當前線程
LockSupport.parkNanos(this, nanos);
}
else
//掛起當前線程
LockSupport.park(this);
}
}
再來看看核心方法
public void run() {
// 前面半句是判斷任務的狀態是不是初始狀態,只有初始狀態的任務才能執行run
// 后面半句是判斷執行該任務的線程是否為空,如果不為空則將當前線程賦值給runner
// 如果任務不為初始狀態 或者 已經有指定的執行線程了 就直接return,這說明已經有線程在執行該任務了
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);
}
//正常完成情況下 調用set方法
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) {
//先將任務狀態置為完成中
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//將任務的返回值置為異常對象
outcome = t;
//將任務置為異常狀態
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
//喚醒所有等待線程
finishCompletion();
}
}
/** 保證所有的強制中斷只下發到正在執行中或者是重置后的任務中
* Ensures that any interrupt from a possible cancel(true) is only
* delivered to a task while in run or runAndReset.
*/
private void handlePossibleCancellationInterrupt(int s) {
// It is possible for our interrupter to stall before getting a
// chance to interrupt us. Let's spin-wait patiently.
if (s == INTERRUPTING)
//如果任務狀態是中斷中,則一直等待
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
// assert state == INTERRUPTED;
// We want to clear any interrupt we may have received from
// cancel(true). However, it is permissible to use interrupts
// as an independent mechanism for a task to communicate with
// its caller, and there is no way to clear only the
// cancellation interrupt.
//
// Thread.interrupted();
}
FutureTask還提供了一個可復用自身的方法。我們注意到run方法中會判斷任務是否是初始狀態,如果不是則不予執行。這意味著一個已經完成的任務是不可能再次被執行的。而FutureTask的runAndReset方法則是讓任務實現復用。
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 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
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}
可以看到幾乎和run方法一樣,但是不同點在于任務執行完畢后并沒有調用set方法,即并沒有改變任務的狀態,也沒有將任務的執行結果保存在outcome中。方法僅在任務成功執行且為初始狀態時返回true。
最后是該類中的一個內部類
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
其實就是一個單向鏈表,保存等待中的線程。
FutureTask中最復雜的方法
/**
* Tries to unlink a timed-out or interrupted wait node to avoid
* accumulating garbage. Internal nodes are simply unspliced
* without CAS since it is harmless if they are traversed anyway
* by releasers. To avoid effects of unsplicing from already
* removed nodes, the list is retraversed in case of an apparent
* race. This is slow when there are a lot of nodes, but we don't
* expect lists to be long enough to outweigh higher-overhead
* schemes.
*/
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;
else if (pred != null) {
pred.next = s;
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
該方法旨在并發情況下能清除掉所有等待某個FutureTask完成的線程節點。
FutureTask全程沒有加鎖,全部是調用Unsafe類的cas方法來實現的。
總結
FutureTask將原始的任務(Callable或者Runnable)封裝了一層,加入了狀態位,并且自己維護狀態。最終提交到線程池的對象其實是一個FutureTask,由于FutureTask實現了Runnable接口,因此線程池執行的其實是FutureTask的run方法。任務的狀態變更都是FutureTask自己完成的,線程池對于FutureTask內部的狀態一無所知。一個FutureTask在執行前被取消,并不意味著線程池不再派出線程去執行FutureTask,線程池照樣會派出線程去執行該FutureTask,只是在執行FutureTask的run方法時,FutureTask判斷自己已經被取消了,就直接return了,不再執行包在其中的原始任務了。