FutureTask
FutureTask可以说是Future的纯粹的实现类了,应用也非常的广泛
先来看看FutureTask实现的接口Future及其定义的方法
Future是什么
A Future represents the result of an asynchronous computation
Future代表异步计算的结果
Future是一个接口,定义了可对异步计算的结果执行的操作
Future的方法
// 用于获取异步计算的结果
V get() throws InterruptedException, ExecutionException;
// 用于获取异步计算的结果,超时则抛出超时异常
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
// 任务是否执行结束
boolean isDone();
// 尝试取消任务
boolean cancel(boolean mayInterruptIfRunning);
// 任务是否取消成功
boolean isCancelled();
FutureTask的组成
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
FutureTask实现了RunnableFuture,而RunnableFuture又继承了Runnable和Future
也就是FutureTask中也需要实现run方法
再看看FutureTask中的成员变量,FutureTask有五个成员变量
// FutureTask的状态
private volatile int state;
// FutureTask实际执行的任务
private Callable<V> callable;
// 执行任务返回的结果
private Object outcome; // non-volatile, protected by state reads/writes
// 执行任务的线程
private volatile Thread runner;
// 等待队列,存放等待任务执行完毕的线程
private volatile WaitNode waiters;
FutureTask获取异步计算的返回值
下面这段代码是FutureTask最简洁明了的用法,也是执行异步任务并获取返回值的最原始的做法
最原始的东西越能看清本质
// 定义一个返回类型为String的异步任务
// 这里的构造函数传入的是Callable
FutureTask<String> futureTask = new FutureTask<>(() -> {
int a = 1, b = 2;
return String.valueOf(a + b);
});
// 随便开启一个线程,执行这个异步任务
new Thread(futureTask).start();
// 通过get获取这个异步任务的结果
try {
String s = futureTask.get();
System.out.println(s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
输出:
3
为什么要专门创建一个FutureTask呢?为什么不能直接把Callable直接传入Thread的构造函数呢?
答案很简单,Thread在jdk1.0就已经存在了,而Callable作为juc的产物,是在jdk1.5之后才引入的,Thread的所有构造函数中,都只能传入Runnable,没有传入Callable,而Runnable的run是无返回值的,Callable的call才有返回值
那要怎么办呢?
这里就轮到FutureTask登场了
FutureTask实现了Runnable,所以它可以传入Thread的构造函数,但是这样是不够的,因为只到这里这个FutureTask仅仅只是一个普通的任务罢了,我们要的是可以获取执行结果的任务
所以还需要它的两个成员变量callable和outcome
outcome字面意思就是任务输出的结果,任务还没跑起来,这个outcome就是null
callable的值是啥?这个callable就是FutureTask构造函数中传入的callable
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
outcome有了,callable也有了,也能传入Thread了,那是任务怎么跑起来的呢?
我们知道,在调用Thread的start之后,会调用start0,然后会执行Thread中的run方法,在不重写run方法的时候,run方法是这样跑的
// Thread.run
@Override
public void run() {
if (target != null) {
target.run();
}
}
这个target就是传入的Runnable,还记得我们一开始往Thread的构造函数中传入的是什么吗?
new Thread(futureTask).start();
我们传入的是futureTask,也就是说start0之后,线程会执行futureTask中的run方法
那我们继续追溯futureTask的run方法
// FutureTask.run
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
// 获取callable
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// 执行callable的call方法
// 执行异步任务,并获取call方法的执行结果
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);
}
}
我们先关心核心的逻辑
在FutureTask的run方法中,执行了callable的call方法,而call方法就是我们要执行的异步任务,不仅如此,它还根据了callable的特性,获取到了call方法的返回结果,也就是异步任务的返回结果
那这个结果后面去了哪里呢?future.get是怎么获取到这个结果的呢?
继续追溯这个result,发现它被FutureTask的set方法处理了
if (ran)
set(result);
// FutureTask.set
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
在这个set方法中,用到了cas,先不管
我们只需要知道cas成功之后,这个返回值就被赋给了outcome;这个finishCompletion后面会讲到,留意一下
现在outcome已经得到了,我们回到最初的FutureTask.get
// FutureTask.get
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
这里返回了report(s)的结果,也就是我们的outcome
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);
}
总结
Thread.start-->start0-->Thread.run-->FutureTask.run-->Callable.call-->FutureTask.set-->FutureTask.report-->FutureTask.get
再说一下使用FutureTask来完成获取异步任务结果的这个操作,其实体现了一种设计模式,叫适配器模式
FutureTask适配了Thread和Callable
Thread不能传入Callable,那么可以传入FutureTask,并且在FutureTask中通过成员变量保存Callable,并在FutureTask的run中执行Callable的call并获取call的返回值,最后由FutureTask.get来获取结果
FutureTask的等待和唤醒机制
上面简述了FutureTask是怎么获取异步任务的结果,但是中间遗漏了一个很重要的环节
我们都知道get方法是阻塞的,在任务执行完毕之前,线程是会等待任务执行完毕的
那这些线程都在做什么呢?FutureTask是怎么管理这些阻塞的线程的呢?这些线程什么时候会被唤醒呢?是怎么被唤醒的呢?
我们回到FutureTask.get
// FutureTask.get
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
会发现如果FutureTask的状态如果小于等于COMPLETING,那么就会调用awaitDone阻塞并等待任务执行完毕
和juc下的线程池、AQS等一样,FutureTask中也有不少状态,这里简单说说FutureTask的状态
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;
/*
Possible state transitions:
NEW -> COMPLETING -> NORMAL
NEW -> COMPLETING -> EXCEPTIONAL
NEW -> CANCELLED
NEW -> INTERRUPTING -> INTERRUPTED
*/
FutureTask是怎么管理这些阻塞的线程的呢?
在说awaitDone做了什么之前,先说一下FutureTask是怎么管理这些阻塞的线程
每个调用FutureTask.get的线程,在任务还没结束时,就会把这个线程封装成一个节点,插入到等待队列中,并阻塞该线程,直到任务执行结束才被唤醒(暂不考虑被中断唤醒)
在FutureTask中,用到了另外一个成员变量作为等待队列,waiters,这是一个由单链表实现的等待队列;相同的设计还有AQS
private volatile WaitNode waiters;
WaitNode是FutureTask中的静态内部类,结构如下:
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
可以看出它的结构非常简单,单纯就是在Thread之上封装了一个next指针而已
它的目的就是把等待的线程封装为节点并存储起来,方便等任务执行结束之后唤醒这些线程
awaitDone做了什么?
知道了FutureTask怎么管理这些线程之后,我们来通过源码验证一下
这里先不考虑过期时间,也就是timed为false,nanos为0L
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 (;;) {
// FutureTask.get响应中断,不断检查中断状态
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
// 任务已经执行完毕,已经给结果赋值,可能成功,可能失败,但不论如何都不用等了,退出awaitDone
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
// 任务已经执行完毕,正在给结果赋值
else if (s == COMPLETING) // cannot time out yet
// 让出cpu
Thread.yield();
// 任务还没开始执行
else if (q == null)
// 创建一个WaitNode来包装当前线程,
// 在WaitNode的构造方法中,把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;
}
// 带超时时间的park
LockSupport.parkNanos(this, nanos);
}
// 不允许超时
else
// 不带超时时间的park
LockSupport.park(this);
}
}
这些线程什么时候会被唤醒呢?是怎么被唤醒的呢?
在FutureTask.get中阻塞的线程会在任务执行完毕之后被唤醒
// FutureTask.get
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L); // 阻塞在这里
return report(s); // 获取结果在这里
}
那么是谁把它们唤醒的呢?
那当然就是执行异步任务的线程了
在任务执行完毕之后,执行异步任务的线程会调用FutureTask.set方法,
// FutureTask.set
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
在这个set方法中调用了finishCompletion方法,在这个方法中逐个唤醒等待队列的线程
// FutureTask.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
}
总结
调用FutureTask.get之后,如果任务还没结束,那么会调用awaitDone,把本线程封装成WaitNode放到等待队列中并等待执行任务的线程唤醒
FutureTask的异常处理机制
在平时使用FutureTask.get的时候,经常会收到捕获异常的提示,要求我们捕获InterruptedException和ExecutionException,如果加入了超时时间,要求捕获TimeoutException
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
那它是怎么抛出这些异常的呢?
InterruptedException是在awaitDone中抛出的,Future设计的时候,是希望Future.get方法是响应中断的,那么在被中断时,会抛出中断异常
// 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()) {
removeWaiter(q);
throw new InterruptedException();
}
// 省略。。。
}
}
ExecutionException是在report中抛出的,当任务是异常结束时,就会把异常封装为ExecutionException再抛出
执行任务的线程在执行的过程中捕获到了异常,则会调用setException
// FutureTask.run
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 {
// 省略。。。
}
}
在setException中会去设置异常状态,并唤醒所有等待队列的线程
// FutureTask.setException
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
等待队列被唤醒的线程则根据state任务执行异常,并抛出ExecutionException
// FutureTask.report
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);
}
当然还有在任务取消的时候会抛出CancellationException,但它是RuntimeException的子类,所以不强制要求捕获
FutureTask的取消任务机制
最后来说说FutureTask是怎么取消任务的
先看Future接口,在Future中定义了cancel方法,用于取消任务
这个方法有两种模式,一种是取消模式,一种是中断模式(没有这种叫法,随便取得名字)
区别在于
中断模式下,调用cancel之后会中断正在执行任务的线程,状态设置为INTERRUPTED
取消模式下,调用cancel只是将任务的状态设置为CANCELLED
// FutureTask.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;
}
不管是哪种模式都会调用finishCompletion将所有等待队列中的线程唤醒
//FutureTask.report
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
// 任务被取消,抛出任务取消异常
// INTERRUPTING、INTERRUPTED状态值均大于CANCELLED
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
需要注意的是,这里取消任务并不是直接把正在执行任务的线程给杀死,也不是立刻停掉任务
如果是取消模式,那么对执行任务的线程是没有一点影响的
如果是中断模式,那么会中断一次执行任务的线程
因为此时执行任务的线程正在跑FutureTask.run中的Callable.call任务,调用cancel的线程是无法通过FutureTask来停止它的,最多只能中断它,如果任务正好是不响应中断的,那也只能任由它跑完,所以取消任务并不是停止任务
cancel能影响的就是那些调用FutureTask.get等待任务执行结果的线程,这些线程会被唤醒,然后抛出一个任务取消的异常
做个实验验证一下
// 定义一个返回类型为String的异步任务
// 这里的构造函数传入的是Callable
FutureTask<String> futureTask = new FutureTask<>(() -> {
int a = 1, b = 2;
// LockSupport.park()响应中断,线程在中断后会被唤醒
LockSupport.park();
return String.valueOf(a + b);
});
// 随便开启一个线程,执行这个异步任务
new Thread(futureTask).start();
// 延迟一秒防止call还没执行就被取消
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 取消任务
// 如果传入false,那么不会中断执行任务的线程,程序卡住不动了,因为下面的futureTask.get在等待执行结果,但是任务一直卡在LockSupport.park(),并没有结束
// 如果传入true,那么会中断执行任务的线程,程序往下执行到futureTask.get的时候可以得知任务被取消而抛出任务取消异常
futureTask.cancel(true);
// 通过get获取这个异步任务的结果
try {
String s = futureTask.get();
System.out.println(s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}