介绍
- FutureTask是一种异步任务(或异步计算),举个栗子,主线程的逻辑中需要使用某个值,但这个值需要负责的运算得来,那么主线程可以提前建立一个异步任务来计算这个值(在其他的线程中计算),然后去做其他事情,当需要这个值的时候再通过刚才建立的异步任务来获取这个值,有点并行的意思,这样可以缩短整个主线程逻辑的执行时间。
- 与1.6版本不同,1.7的FutureTask不再基于AQS来构建,而是在内部采用简单的Treiber Stack来保存等待线程。
接口
public interface Future<V> {
//取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束
boolean cancel(boolean mayInterruptIfRunning);
//任务是否已经取消,任务正常完成前将其取消,则返回 true
boolean isCancelled();
//任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true
boolean isDone();
//等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException
V get() throws InterruptedException, ExecutionException;
//同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计算超时,将抛出TimeoutException
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
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常用方式:
1.创建任务,实际使用时,一般会结合线程池(ThreadPoolExecutor)使用,所以是在线程池内部创建FutureTask。
2.执行任务,一般会有由工作线程(对于我们当前线程来说的其他线程)调用FutureTask的run方法,完成执行。
3.获取结果,一般会有我们的当前线程去调用get方法来获取执行结果,如果获取时,任务并没有被执行完毕,当前线程就会被阻塞,直到任务被执行完毕,然后获取结果。
4.取消任务,某些情况下会放弃任务的执行,进行任务取消。
内部结构
public class FutureTask<V> implements RunnableFuture<V> {
/**
* 内部状态可能得迁转过程:
* 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;
/** 内部的callable,运行完成后设置为null */
private Callable<V> callable;
/** 如果正常完成,就是执行结果,通过get方法获取;如果发生异常,就是具体的异常对象,通过get方法抛出。 */
private Object outcome; // 本身没有volatile修饰, 依赖state的读写来保证可见性。
/** 执行内部callable的线程。 */
private volatile Thread runner;
/** 存放等待线程的Treiber Stack*/
private volatile WaitNode waiters;
//所谓的Treiber Stack就是由WaitNode组成的(一个单向链表)。
static final class WaitNode {
volatile Thread thread; //指向block线程
volatile WaitNode next; //下一个node
WaitNode() { thread = Thread.currentThread(); }
}
}
创建
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
}
//以下方法为Executors的方法
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
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;
}
}
必须把state的写放到最后,因为state本身由volatile修饰,所以可以保证callable的可见性。(因为后续读callable之前会先读state,还记得这个volatile写读的HappenBefore规则吧)
状态
/**
* 内部状态可能得迁转过程:
* NEW -> COMPLETING -> NORMAL //正常完成
* NEW -> COMPLETING -> EXCEPTIONAL //发生异常
* NEW -> CANCELLED //取消
* NEW -> INTERRUPTING -> INTERRUPTED //中断
*/
public boolean isCancelled() {
return state >= CANCELLED;
}
//只要不为NEW就表示结束
public boolean isDone() {
return state != NEW;
}
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);
}
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
get,set
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);
}
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
get方法会block直到计算完成。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 (;;) {
//中断,则移除q,抛出IE
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
//处理完,返回,如果q!=null,则把线程解绑
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // 任务正在执行中,COMPLETING是中间状态。
Thread.yield(); //释放CPU
//以下代码:state == NEW,
else if (q == null) // q == null,则创建一个WaitNode,绑定Thread
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);
}
}
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;
}
}
}
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);
}
//继续下一个waiter
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
get方法总结:
1.首先检查当前任务的状态,如果状态表示执行完成,进入第2步。
2.获取执行结果,也可能得到取消或者执行异常,get过程结束。
3.如果当前任务状态表示未执行或者正在执行,那么当前线程放入一个新建的等待节点,然后进入Treiber Stack进行阻塞等待。
4.如果任务被工作线程(对当前线程来说是其他线程)执行完毕,执行完毕时工作线程会唤醒Treiber Stack上等待的所有线程,所以当前线程被唤醒,清空当前等待节点上的线程域,然后进入第2步。
5.当前线程在阻塞等待结果过程中可能被中断,如果被中断,那么会移除当前线程在Treiber Stack上对应的等待节点,然后抛出中断异常,get过程结束。
6.当前线程也可能执行带有超时时间的阻塞等待,如果超时时间过了,还没得到执行结果,那么会除当前线程在Treiber Stack上对应的等待节点,然后抛出超时异常,get过程结束。
run
public void run() {
//不是NEW状态或者设置runner失败,直接退出
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;
//处理可能发生的取消中断(cancel(true))。
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
/**
* 确保cancel(true)产生的中断发生在run或runAndReset方法过程中。
*/
private void handlePossibleCancellationInterrupt(int s) {
// 如果当前正在中断过程中,自旋等待一下,等中断完成。
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
// 这里的state状态一定是INTERRUPTED;
// 这里不能清除中断标记,因为没办法区分来自cancel(true)的中断。
// Thread.interrupted();
}
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;
}
可见runAndReset与run方法的区别只是执行完毕后不设置结果、而且有返回值表示是否执行成功。
cancel
//JDK 1.7
public boolean cancel(boolean mayInterruptIfRunning) {
if (state != NEW)
return false; //如果任务已经执行完毕,返回false。
if (mayInterruptIfRunning) {
//如果有中断任务的标志,尝试将任务状态设置为INTERRUPTING
if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
return false;
//上面设置成功的话,这里进行线程中断。
Thread t = runner;
if (t != null)
t.interrupt();
//最后将任务状态设置为INTERRUPTED,注意这里又是LazySet。
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
}
//如果没有中断任务的标志,尝试将任务状态设置为CANCELLED。
else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
return false;
//最后唤醒Treiber Stack中所有等待线程。
finishCompletion();
return true;
}
//JDK 1.8
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的情况下,内部首先通过一个原子操作将state从NEW转变为INTERRUPTING,然后中断执行任务的线程,然后在通过一个LazySet的操作将state从INTERRUPTING转变为INTERRUPTED,由于后面这个操作对其他线程并不会立即可见,所以handlePossibleCancellationInterrupt才会有一个自旋等待state从INTERRUPTING变为INTERRUPTED的过程。