Future接口用来表示异步执行的结果,比如异步执行一个Callable任务就会返回一个Future对象,通过这个Future对象来获取异步执行的结果
继承关系如下:
public interface Future<V> {
/**
* 1.尝试取消任务,如果任务已经完成或者被取消则会取消失败,也有可能因为其他原因取消失败,方法返回true表示取消成功,
* false表示取消失败,通常是因为任务已经开始了
* 2.如果任务还未开始并且被取消成功,那么这个任务再也不会被执行
* 3.如果任务已经开始,mayInterruptIfRunning参数决定执行该任务的线程是否需要中断任务,true表示正在执行任务的线程需要中断,false表示既然已经开始执行了,就执行完毕吧
* 4.如果方法返回true,那么isDone和isCancelled也会返回true
*/
boolean cancel(boolean mayInterruptIfRunning);
//如果任务在完成之前被取消,返回true
boolean isCancelled();
//如果任务已经完成,返回true,这里的完成不仅仅是代表正常完成,也有可能是异常终止,取消,这些都会返回true
boolean isDone();
//阻塞获取异步执行的结果
V get() throws InterruptedException, ExecutionException;
//指定超时时间的get超时
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();
}
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) {
//使用工具类将Runnable包装成Callable对象
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
//RunnableAdapter将Runnable转换为Callable对象,类很简单,就是实现了Callable对象,
//重写call方法,调用的是Runnable对象的run方法
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;
}
}
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 -> NORMAL
NEW -> COMPLETING -> EXCEPTIONAL
NEW -> CANCELLED
NEW -> INTERRUPTING -> INTERRUPTED
//Callable任务对象
private Callable<V> callable;
//任务结果对象,不是volatile,但是通过任务的状态来保护它的可读性
private Object outcome; // non-volatile, protected by state reads/writes
//执行任务的线程对象
private volatile Thread runner;
//WaitNode对象栈,Treiber stack 是无锁栈
private volatile WaitNode waiters; /** Treiber stack of waiting threads */
public void run() {
//1.设置当前运行任务的线程
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 {
//2.执行任务
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//3.设置异常
setException(ex);
}
//4.设置结果
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
//5.设置状态,处理中断
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
protected void set(V v) {
//1.CAS设置状态为COMPLETING成功,则保存结果
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
//2.设置为最终状态
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
public V get() throws InterruptedException, ExecutionException {
int s = state;
//1.获取状态,如果尚未完成,就等待直到完成
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//2.返回结果
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);
}
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 cancel(boolean mayInterruptIfRunning) {
//1.根据mayInterruptIfRunning将状态从NEW修改为INTERRUPTING或者CANCELLED,修改失败就返回,
//mayInterruptIfRunning为true则将状态修改为INTERRUPTING,反之CANCELLED
if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
//mayInterruptIfRunning为true,需要中断线程
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
//2.清理工作
finishCompletion();
}
return true;
}
private int awaitDone(boolean timed, long nanos) throws InterruptedException {
//1.计算截止时间
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
//2.自旋等待
for (;;) {
//3.线程被中断,抛出异常,get方法是支持中断的,并且会移除已经中断的Waiter等待节点
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
//4.已经完成了,那就将线程置为null,返回线程状态
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//5.COMPLETING状态表示FutureTask执行处于中间状态,线程让出CPU给任务线程执行任务
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//6.构造对象
else if (q == null)
q = new WaitNode();
//7.设置waiter链表,这里的意思我猜是这样的,waiters代表了任务执行完毕之前,调用get获取结果的线程构成的一个waiterNode栈,
//代表当前线程的节点是q,这里把q设置为当前waiter的前驱,然后将waiters变量设置为q,假设有2个线程先后来get获取结果,任务都
//没有执行完毕,那么第二个线程对应的waiterNode就保存在waiter是变量里面,第一个线程就是第二个的后继,像一个链表连接起来
//WaitNode4(线程4) -> WaitNode3(线程3) -> WaitNode2(线程2) -> WaitNode1(线程1)
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q);
//8.如果是超时模式,就考虑是否超时,没有超时就使用LockSupport挂起线程
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
//1.将WaitNode置为null
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
//2.设置成功之后自旋
for (;;) {
//3.将线程对象置为null
Thread t = q.thread;
if (t != null) {
q.thread = null;
//4.唤醒线程继续执行,因为任务都被取消或者异常了,等待的线程就不能在继续傻等了,该起身走了
LockSupport.unpark(t);
}
//4.如果没有后继,就break
WaitNode next = q.next;
if (next == null)
break;
//5.如果有后继,就把前驱的next指针置为null(帮助gc),并处理后继节点
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
//6.调用钩子方法
done();
//7.成员变量置null
callable = null; // to reduce footprint
}
WaitNode4(线程4) -> WaitNode3(线程3) -> WaitNode2(线程2) -> WaitNode1(线程1)
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
protected void done() { }
private final BlockingQueue<Future<V>> completionQueue;
private class QueueingFuture extends FutureTask<Void> {
QueueingFuture(RunnableFuture<V> task) {
super(task, null);
this.task = task;
}
//执行完毕之后,将Future结果对象加到阻塞队列中
protected void done() { completionQueue.add(task); }
private final Future<V> task;
}