JDK的Future原始碼解析
zJDK的Future模式中,和Future相關的API有:
介面Callable:有返回結果並且可能丟擲異常的任務;
介面Runnable:沒有返回結果
介面Future:表示非同步執行的結果;
類FutureTask:實現Future、Runnable等介面,是一個非同步執行的任務。可以直接執行,或包裝成Callable執行;
1.Callable/Runnable
java.lang.Runnable介面只聲明瞭一個run方法:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
java.util.concurrent.Callable只宣告一個Call()方法:
@FunctionalInterface
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;
}
這是個泛型介面,call函式返回的型別就是傳進來的v型別;
Callable一般情況下是配合ExecutorService來使用的,在ExecutorService介面中聲明瞭若干個submit方法的過載版本,看java.util.concurrent.ExecutorService原始碼:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
2 Future介面
Future就是對於具體的Runnable或者Callable任務的執行結果進行取消、查詢是否完成、獲取結果。必要時可以通過get方法獲取執行結果,該方法會阻塞直到任務返回結果。
java.util.concurrent.Future介面:
* @see FutureTask
* @see Executor
* @since 1.5
* @author Doug Lea
* @param <V> The result type returned by this Future's {@code get} method
*/
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
在Future介面中聲明瞭5個方法:
cancel方法用來取消任務,如果取消任務成功則返回true,如果取消任務失敗則返回false。引數mayInterruptIfRunning表示是否允許取消正在執行卻沒有執行完畢的任務。如果任務已經完成,則無論mayInterruptIfRunning為true還是false,此方法肯定返回false;如果任務正在執行,若mayInterruptIfRunning設定為true,則返回true,若mayInterruptIfRunning設定為false,則返回false;如果任務還沒有執行,則無論mayInterruptIfRunning為true還是false,肯定返回true。
isCancelled方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true。
isDone方法表示任務是否已經完成,若任務完成,則返回true;
get()方法用來獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回;
get(long timeout, TimeUnit unit)用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。
Future提供了三種功能:
1)判斷任務是否完成;
2)能夠中斷任務;
3)能夠獲取任務執行結果。
3 FutureTask
3.1 FutureTask類
FutureTask類實現了RunnableFuture介面:
public class FutureTask<V> implements RunnableFuture<V> {
而RunnableFuture繼承了Runnable介面和Future介面:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
所以FutureTask既可以作為Runnable被執行緒執行,又可以作為Future得到Callable的返回值。
3.2 state欄位
volatile修飾的state欄位;
/**
* 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;
3.3其他變數
runner和waiters為volatile型別
/** 任務 */
private Callable<V> callable;
/** 儲存結果*/
private Object outcome; // non-volatile, protected by state reads/writes
/** 執行任務的執行緒*/
private volatile Thread runner;
/** get方法阻塞的執行緒佇列 */
private volatile WaitNode waiters;
3.4構造器
FutureTask有2個構造器:
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
}
這兩個建構函式區別在於,如果使用第一個建構函式最後獲取執行緒實行結果就是callable的執行的返回結果;而如果使用第二個建構函式那麼最後獲取執行緒實行結果就是引數中的result,接下來讓我們看一下FutureTask的run方法
3.5CAS工具初始化
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
3.6 get方法的等待佇列
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
3.7 run方法
public void run() {
//如果狀態不是new,或者runner舊值不為null,就結束
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);
}
//如果正常完成,就設定result和state
if (ran)
set(result);
}
} finally {
// 設定runner為null,阻止結束後再呼叫run()方法
runner = null;
// 重讀state,防止中斷洩露
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
其中,catch語句中的setException(ex)如下:
//發生異常時設定state和outcome
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // 喚醒get()方法阻塞的執行緒
finishCompletion();
}
}
而正常完成時,set(result);方法如下:
//正常完成時,設定state和outcome
protected void set(V v) {
//正常完成時,NEW->COMPLETING->NORMAL
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
// 喚醒get方法阻塞的執行緒
finishCompletion();
}
}
而喚醒get方法阻塞的執行緒方法如下:
//移除並喚醒所有等待的執行緒,呼叫done,並清空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
}
重點看一下handlePossibleCancellationInterrupt方法, 這個方法是自旋等待state變為INTERRUPTED(對應cancel方法的結束),即等待中斷的結束。
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();
}
3.8 get方法解析
get()方法有2種:
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);
}
new狀態的Futuretask的get將會阻塞。
get() 方法中涉及到 awaitDone 方法, 將awaitDone的執行結果賦值給state, 最後report方法根據state值進行返回相應的值, 而awaitDone是整個 FutureTask 執行的核心。
那下面來看 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 (;;) {
// 重置中斷狀態並返回之前的中斷狀態
if (Thread.interrupted()) {
//如果已經被中斷過,則移除q
removeWaiter(q);
//並丟擲中斷異常
throw new InterruptedException();
}
int s = state;
//如果已經成為終止狀態,則返回state的值
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//如果設定結果,馬上就能完成,則自旋等待
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//為NEW,正在執行或者還沒開始,就構建新節點給q
else if (q == null)
q = new WaitNode();
//判斷是否入隊,新建節點一般在下一次迴圈入隊阻塞
else if (!queued)
//沒有入隊則入隊
//設定q.next=waiters,然後再將waiter CAS設定為q
queued = UNSAFE.compareAndSwapObject(this,waitersOffset, q.next = waiters, q);
//如果有超時限制,判斷是否超時
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
//超時則移除節點
removeWaiter(q);
return state;
}
阻塞get()方法的執行緒,有超時限制
LockSupport.parkNanos(this, nanos);
}
//已經入隊則繼續阻塞
else
//阻塞get()方法的執行緒,無超時限制
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;
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;
}
}
}