Java異步——FutureTask源碼解析
1. Runnable、Callable、Future、FutureTask的區別與聯係
和Java異步打交道就不能回避掉Runnable
,Callable
,Future
,FutureTask
等類,首先來介紹下這幾個類的區別。
1.1 Runnable
Runnable接口是我們最熟悉的,它隻有一個run函數。然後使用某個線程去執行該runnable即可實現多線程,Thread類在調用start()函數後就是執行的是Runnable的run()函數。Runnable最大的缺點在於run函數沒有返回值。
1.2 Callable
Callable接口和Runnable接口類似,它有一個call函數。使用某個線程執行Callable接口實質就是執行其call函數。call方法和run方法最大的區別就是call方法有返回值:
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
1.3 Future
Future就是對於具體的Runnable或者Callable任務的執行結果進行取消、查詢是否完成、獲取結果、設置結果操作。get
方法會阻塞,直到任務返回結果(Future簡介)。
1.4 FutureTask
Future隻是一個接口,在實際使用過程中,諸如ThreadPoolExecutor返回的都是一個FutureTask實例。
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
可以看到,FutureTask是一個RunnableFuture,而RunnableFuture實現了Runnbale又實現了Futrue這兩個接口。
2 FutureTask的構造過程
事實上,通過ExecutorService接口的相關submit方法,實際上都是提交的Callable或者Runnable,包裝成一個FutureTask對象。
public abstract class AbstractExecutorService implements ExecutorService {
...
//將Runable包裝成FutureTask之後,再調用execute方法
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
//調用newTaskFor方法,利用Callable構造一個FutureTask對象
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
}
可以看到AbstractExecutorService
的submit方法調用後返回的就是一個FutureTask對象,接下來看下FutureTask的構造方法:
//接受Callable對象作為參數
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
//接受Runnable對象作為參數
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);//將Runnable轉為Callable對象
this.state = NEW;
}
//callable方法,將Runnable轉為一個Callable對象,包裝設計模式
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
//RunnableAdapter是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;
}
}
可以看到,構造FutureTask時,無論傳入的是Runnable還是Callable,最終都實現了Callable接口。
3 FutureTask主要成員
接下來看下FutureTask類的主要成員變量:
public class FutureTask<V> implements RunnableFuture<V> {
/*
* FutureTask中定義了一個state變量,用於記錄任務執行的相關狀態 ,狀態的變化過程如下
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
private volatile int state;
//主流程狀態
private static final int NEW = 0; //當FutureTask實例剛剛創建到callbale的call方法執行完成前,處於此狀態
private static final int COMPLETING = 1; //callable的call方法執行完成或出現異常時,首先進行此狀態
private static final int NORMAL = 2;//callable的call方法正常結束時,進入此狀態,將outcom設置為正常結果
private static final int EXCEPTIONAL = 3;//callable的call方法異常結束時,進入此狀態,將outcome設置為拋出的異常
//取消任務執行時可能處於的狀態
private static final int CANCELLED= 4;// FutureTask任務尚未執行,即還在任務隊列的時候,調用了cancel方法,進入此狀態
private static final int INTERRUPTING = 5;// FutureTask的run方法已經在執行,收到中斷信號,進入此狀態
private static final int INTERRUPTED = 6;// 任務成功中斷後,進入此狀態
private Callable<V> callable;//需要執行的任務,提示:如果提交的是Runnable對象,會先轉換為Callable對象,這是構造方法參數
private Object outcome; //任務運行的結果
private volatile Thread runner;//執行此任務的線程
//等待該FutureTask的線程鏈表,對於同一個FutureTask,如果多個線程調用了get方法,對應的線程都會加入到waiters鏈表中,同時當FutureTask執行完成後,也會告知所有waiters中的線程
private volatile WaitNode waiters;
......
}
FutureTask的成員變量並不複雜,主要記錄以下幾部分信息:
- 狀態
- 任務(callable)
- 結果(outcome)
- 等待線程(waiters)
4 FutureTask的執行過程
4.1 run
接下來開始看一個FutureTask的執行過程,FutureTask執行任務的方法當然還是run方法:
public void run() {
//保證callable任務隻被運行一次
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);
}
}
- 如果狀態不為new或者運行線程runner失敗,說明當前任務已經被其他線程啟動或者已經被執行過,直接返回false
- 調用call方法執行核心任務邏輯。如果調用成功則執行set(result)方法,將state狀態設置成NORMAL。如果調用失敗拋出異常則執行setException(ex)方法,將state狀態設置成EXCEPTIONAL,喚醒所有在get()方法上等待的線程
- 如果當前狀態為INTERRUPTING(步驟2已CAS失敗),則一直調用Thread.yield()直至狀態不為INTERRUPTING
4.2 set、setException方法
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
兩個方法的邏輯基本一致,先通過CAS操作將狀態從NEW置為COMPLETING,然後再將最終狀態分別置為NORMAL或者EXCEPTIONAL,最後再調用finishCompletion方法。
4.3 finishCompletion
private void finishCompletion() {
for (WaitNode q; (q = waiters) != null;) {
//通過CAS把棧頂的元素置為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
}
finishCompletion的邏輯也比較簡單:
- 遍曆waiters鏈表,取出每一個節點:每個節點都代表一個正在等待該FutureTask結果(即調用過get方法)的線程
- 通過 LockSupport.unpark(t)喚醒每一個節點,通知每個線程,該任務執行完成
4.4 get
在finishCompletion方法中,FutureTask會通知waiters鏈表中的每一個等待線程,那麼這些線程是怎麼被加入到waiters鏈表中的呢?上文已經講過,當在一個線程中調用了get方法,該線程就會被加入到waiters鏈表中。所以接下來看下get方法:
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);
}
get方法很簡答,主要就是調用awaitDone
方法:
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
//如果該線程執行interrupt()方法,則從隊列中移除該節點,並拋出異常
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
//如果state狀態大於COMPLETING 則說明任務執行完成,或取消
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//如果state=COMPLETING,則使用yield,因為此狀態的時間特別短,通過yield比掛起響應更快。
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);
//如果需要阻塞指定時間,則使用LockSupport.parkNanos阻塞指定時間
//如果到指定時間還沒執行完,則從隊列中移除該節點,並返回當前狀態
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
//阻塞當前線程
else
LockSupport.park(this);
}
}
整個方法的大致邏輯主要分為以下幾步:
- 如果當前狀態值大於COMPLETING,說明已經執行完成或者取消,直接返回
- 如果state=COMPLETING,則使用yield,因為此狀態的時間特別短,通過yield比掛起響應更快
- 如果當前線程是首次進入循環,為當前線程創建wait節點加入到waiters鏈表中
- 根據是否定時將當前線程掛起(
LockSupport.parkNanos
LockSupport.park
)來阻塞當前線程,直到超時或者線程被finishCompletion方法喚醒 - 當線程掛起超時或者被喚醒後,重新循環執行上述邏輯
get方法是FutureTask中的關鍵方法,了解了get方法邏輯也就了解為什麼當調用get方法時線程會被阻塞直到任務運行完成。
4.5 cancel
cancel方法用於結束當前任務:
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
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
- 根據mayInterruptIfRunning是否為true,CAS設置狀態為INTERRUPTING或CANCELLED,設置成功,繼續第二步,否則返回false
- 如果mayInterruptIfRunning為true,調用runner.interupt(),設置狀態為INTERRUPTED
- 喚醒所有在get()方法等待的線程
最後更新:2017-07-16 23:02:35