FutureTask类是JDK中对并行程序设计中异步模式提供的支持,采用异步模式而不是同步模式来设计程序,可以起到解耦的目的,下面我们直接看FutureTask类的源码(JDK8):
先看主要的成员变量和构造函数:
public class FutureTask<V> implements RunnableFuture<V> {
private volatile int state; // 异步任务的状态,一共有7种
// 7种状态
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;
/*
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
/** The underlying callable; nulled out after running */
private Callable<V> callable; // 异步任务
/** The result to return or exception to throw from get() */
private Object outcome; // 异步结果
/** The thread running the callable; CASed during run() */
private volatile Thread runner; // 执行异步任务的线程
/** Treiber stack of waiting threads */
private volatile WaitNode 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); // 使用适配器设计模式将Runnable包装成Callable
this.state = NEW; // ensure visibility of callable
}
}
可以看到异步任务的提交也是有状态之间的转换,在FutureTask类中一共定义了7中状态,分别是:NEW,COMPLETING,NORMAL,EXCEPTIONAL,CANCELLED,INTERRUPTING与INTERRUPTED,并且在源码中也给出了状态之间的转换的路径。另外,FutureTask类中一共定义了5个实例变量,分别为:state(表示异步任务的状态),callable(异步任务),outcome(异步任务的结果),runner(执行异步任务的线程),waiters(等待异步结果而被阻塞的线程---基于单向链表)。有两个public构造函数,分别接受callable与runnable任务,使用适配器模式将runnable适配为callable。
从类的继承体系上我们可以看出,FutureTask类实现了RunnableFuture接口,表示一个可运行的异步任务,我们来看看RunnableFuture接口定义了那些方法:
public interface RunnableFuture<V> extends Runnable, Future<V> {
}
可以看到RunnableFuture接口并没有定义新的方法,只是继承了Runnable与Future接口,Runnable接口我们已经非常熟悉了,里面只有一个run方法,下面我们来具体看看Future接口里面定义了那些方法。
public interface Future<V> {
// 取消异步任务的执行,如果任务已经开始执行,mayInterruptIfRunning表示是否中断正在执行的线程
boolean cancel(boolean mayInterruptIfRunning);
// 判断任务是否已经取消
boolean isCancelled();
// 判断任务是否已经完成,任务正常结束,抛出异常,或者被取消了,都放回true
boolean isDone();
// 阻塞获取异步结果
V get() throws InterruptedException, ExecutionException;
// 阻塞一段时间获取异步结果
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
可以看到Future类提供了一些方法来控制异步任务的执行,包括取消任务,判断任务是否已经完成,取得异步结果。
明白了FutureTask类的继承关系与主要的成员变量后,我们来看看其具体的实现:
先看看一些私有的方法:
// 等待异步结果的线程,采用单向链表来实现
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
// 根据状态(NORMAL,CANCELLED,EXCEPTIONAL)来报告结果
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 boolean isCancelled() {
return state >= CANCELLED;
}
// 判断任务是否已经完成
public boolean isDone() {
return state != NEW;
}
// 通过CAS设置异步结果的状态,NORMAL情况
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
// 通过CAS设置异步状态,(异常状态)
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
// 任务完成后执行的逻辑,就算唤醒所有阻塞等待异步结果的线程
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
}
protected void done() { } // 用于子类重写,实现自己的逻辑,异步任务完成后都会执行。
// 由于种种原因,(超时,中断)取消等待结果线程
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; // 带标签的continue语句
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset, q, s)) // 该结点为头结点
continue retry;
}
break;
}
}
}
// 等待异步结果的完成
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();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this); // 阻塞当前线程
}
}
下面来看看主要函数的实现:
// 取消异步任务
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;
}
// 阻塞获取异步结果
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
// 超时等待获取异步结果
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 void run() {
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 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);
}
}
最后看看CAS相关:
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);
}
}
比较简单,通过Unsafe获取对应变量在FutureTask类中的偏移量。
可以看到,FutureTask类整体上来说还是比较清晰的,它提供了Java中异步任务的执行框架。