一、整体框架
1.1 Callable
-
可以返回结果并可能抛出异常的任务
-
类似于 java.lang.Runnable 接口,两者都是为类实例可能由另一个线程执行的场景设计的。 但是,Runnable不会返回结果,也不会抛出受检异常。
-
Executors类包含从其他常见形式转换为Callable类的实用方法
/** * 计算结果,如果处理出错,则抛出异常。 * @throws Exception if unable to compute a result */ V call() throws Exception;
1.2 Future
- 用于表示异步任务的结果。 提供了检查任务是否完成、等待其完成以及获取任务结果的方法。 结果只能在任务完成后使用get方法获取,支持任务完成之前的阻塞功能。 通过cancle方法可以取消任务,任务完成后无法取消。
- 异步任务中的行为happen-before在另一个线程中对应Future.get()之后的行为
/**
* 等待任务完成,并获取结果
*
* @return the computed result
* @throws CancellationException:任务被取消
* @throws ExecutionException:任务执行过程抛了异常
* @throws InterruptedException:当前线程等待过程中被中断
*/
V get() throws InterruptedException, ExecutionException;
/**
* 等待任务完成,并获取结果,但存在超时时间
*
* ...
* @throws TimeoutException if the wait timed out
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
/**
* 尝试取消任务的执行。
* 如果任务已完成、已被取消或由于某些原因无法取消,则此尝试将失败。
* 如果成功,并且在调用cancle方法时此任务尚未启动,则此任务不会执行。
* 如果任务已经开始,则mayInterruptIfRunning参数决定是否中断执行此任务的线程以尝试停止任务。
* 此方法返回后,对isDone的后续调用将始终返回true。
* 如果此方法返回true,则对isCancelled的后续调用将始终返回true。
*
* @param mayInterruptIfRunning
{@code true}:执行任务的线程应该被中断
{@code false}:处理中的任务允许执行完成
* @return {@code false}:任务无法取消
* {@code true} :otherwise
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* 如果此任务在正常完成之前被取消,则返回true
*/
boolean isCancelled();
/**
* 如果此任务完成,则返回true
*
* 完成可能是由于正常终止、异常或取消。这些情况下,都返回true。
*/
boolean isDone();
1.3 RunnableFuture
- 继承自Runnable接口和Future接口,可以理解为A Future that is Runnable。
- RunnableFuture的run方法成功执行意味着Future完成并可以访问其结果
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
二、FutureTask实现原理
- FutureTask可用于包装Callable或Runnable对象。 因为其实现了Runnable,所以可以将FutureTask提交给Executor执行
- FutureTask实现了Runnable,又聚合了Callable,还提供了两者一系列的转化方法,这样FutureTask就统一了Callable和Runnable
2.1 任务运行状态
/**
* 任务的运行状态,初始值为NEW。
* 状态仅在set、setException和cancel方法中会转换为终态。
* 状态可能处于COMPLETING(设置结果时)或INTERRUPTING(cancle(true)中断任务)的中间态。
* 从这些中间状态到最终状态的转换通过更简单的有序/惰性写入实现
*
* 可能的状态流转:
* 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;
- NEW:初始状态,表示是个新的任务或者还没被执行完的任务
- COMPLETING:NEW->COMPLETING发生在任务已经执行完成或者任务执行异常的时候,此时执行结果或者异常原因还没有保存到outcome字段,这个状态会时间较短,属于中间态。
- NORMAL:任务执行完成并且执行结果已保存到outcome字段,状态COMPLETING->NORMAL,为终态。
- EXCEPTIONAL:执行异常且异常原因已保存到outcome字段,状态COMPLETING->EXCEPTIONAL,为终态。
- CANCELLED:任务未开始执行或者开始执行但未完成,调用cancel(false)取消任务且不中断任务执行线程,状态NEW->CANCELLED,为终态。
- INTERRUPTING:任务未开始执行或者开始执行但未完成,调用cancel(true)取消任务且要中断执行线程但未真正中断之前,状态NEW->INTERRUPTING,为中间态。
- INTERRUPTED:调用interrupt()中断执行线程之后,状态INTERRUPTING->INTERRUPTED,为终态。
2.2 成员变量与构造器
/** 聚合的callable对象; 运行后清空 */
private Callable<V> callable;
/** 从 get() 返回的结果或抛出的异常 */
private Object outcome; // non-volatile, protected by state reads/writes
/** 执行callable任务的线程 */
private volatile Thread runner;
/** get()方法时被等待的线程,Treiber stack */
private volatile WaitNode waiters;
/**
* 创建一个FutureTask,将在运行时执行给定的Callable任务
*/
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
/**
* 创建一个FutureTask,将在运行时执行给定的Runnable任务,get()将在成功完成时返回传入的result。
*
* @param result:成功完成后返回的结果。如果不需要特定结果,可以如下构造:
* {@code Future<?> f = new FutureTask<Void>(runnable, null)}
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
-
通过RunnableAdapter的设计将 Runnable 和 Callable 灵活地打通:
/** * A callable that runs given task and returns given 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; } }
2.3 get()方法实现原理
//无限阻塞获取结果
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);
}
//返回结果 or 抛出异常
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x; //任务正常执行完成返回结果
if (s >= CANCELLED) //CANCELLED、INTERRUPTED
throw new CancellationException();
throw new ExecutionException((Throwable)x); //EXCEPTIONAL
}
//等待任务完成 or 在超时、中断时终止
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; //thread置空意味着退出竞争
return s;
}
else if (s == COMPLETING)
//如果正在执行,当前线程让出cpu,重新竞争,防止cpu飙高
Thread.yield();
else if (q == null)
//新建waitNode,当前线程就是waitNode的属性
q = new WaitNode();
else if (!queued)
//尝试将当前waitNode放到waiters表头,若成功则后续不会再执行
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
//若已经超时,则移除当前waitNode,返回执行结果
removeWaiter(q);
return state;
}
//当前线程TIMED_WAITING
LockSupport.parkNanos(this, nanos);
}
else
//没有设置超时时间,当前线程转为WAITING状态
LockSupport.park(this);
}
}
2.3 run()方法实现原理
public void run() {
//1.当前任务的state如果不为NEW则说明任务或者已经执行过,或者已经被取消,直接返回。
//2.把任务执行线程引用CAS地保存在runner字段中,如果保存失败,说明已经有线程在执行该任务了,直接返回(保证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 {
//state终态后,runner置为null,在终态之前runner必须非null以防止并发调用 run()
runner = null;
//runner置为null后重新读取state防止中断操作的泄露
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
-
如果任务执行发生异常,则调用setException()方法保存异常信息
protected void setException(Throwable t) { //CAS地把当前的状态从NEW变更为COMPLETING状态(确保没有被set或者取消) if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { //把异常原因保存在outcome字段中 outcome = t; UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state finishCompletion(); } }
- putOrderedInt保证写不被重排序,但不强制将store buffer里的数据刷新到内存,即别的线程读state时可能看不到state的更新,存在一定延迟性。如果正巧一个线程putOrderedInt完,另一个线程立马要读这个state,没读到更新,主动yield,这样会浪费一点cpu,并发生线程切换的资源消耗。FutureTask的作者应该是认为,这种低概率下产生的成本消耗要优于每次写都要强刷store buffer的固定成本消耗。
-
run 方法没有返回值,通过set(result)给 outcome 属性赋值,get 时就能从 outcome 属性中拿到返回值
protected void set(V v) { //CAS地把当前的状态从NEW变更为COMPLETING状态(确保没有被set或者取消) if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { //把异常原因保存在outcome字段中 outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
2.4 cancel()方法实现原理
public boolean cancel(boolean mayInterruptIfRunning) {
//1.不是NEW状态不能cancle直接返回false
//2.mayInterruptIfRunning: true,CAS设置状态为INTERRUPTING
// mayInterruptIfRunning: false,CAS设置状态为CANCELLED
// 设置失败返回false
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
//1.调用runner.interupt()中断任务执行的线程
//2.设置状态为INTERRUPTED
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
- cancle(true)会尝试直接中断任务执行线程,cancle(false)则允许任务执行线程将任务执行完成
- cancel(true)并不一定能够停止正在执行的异步任务:Thread.interrupt()方法只是设置中断标志位,如果被中断的线程处于sleep()、wait()或者join()逻辑中则会抛出InterruptedException异常
2.5 finishCompletion()方法实现原理
- 任务执行异常、正常执行完毕,或者取消任务,最后都会调用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
}
2.6 isCancled()和isDone()
public boolean isCancelled() {
return state >= CANCELLED;//CANCELLED INTERRUPTED
}
public boolean isDone() {
return state != NEW;
}