在java中如果我们希望执行一段代码,但是我们当前不关心他的执行结果,而是在另一个时刻去异步获取其返回结果,就可以用到Future。如下:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(() -> {
Thread.sleep(1000L);
return "success";
});
new Thread(() -> {
try {
System.out.println(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();
System.out.println(future.get());
通过Executors.newSingleThreadExecutor()创建了ThreadPoolExecutor,所以进去ThreadPoolExecutor的submit方法
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
// AbstractExecutorService下的方法
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
可以看到 ftask 是一个 FutureTask 并调用了其get方法
在进入get方法前先看看 FutureTask 有哪些属性
/**
* Possible state transitions:
* 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; // 任务已被中断
private Callable<V> callable; // 执行返回的Callable 也就是真正要执行的任务
private Object outcome; // 最终的返回结果
private volatile Thread runner; // 执行获取返回结果的线程
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
}
现在进入其get方法,看看是如何进入阻塞的
// 一直阻塞直到结果返回
public V get() throws InterruptedException, ExecutionException {
int s =state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
// 阻塞一定时长,超过时长任务没处理完就抛出 TimeoutException
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);
}
这里重点的是 awaitDone 阻塞判断,以及 report 返回数据
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; // 获取任务状态,这个state是 volatile 的所以直接获取
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // 任务执行中 当前线程放弃CPU进入就绪状态
Thread.yield();
// 下面情况 s < COMPLETING 也就只有NEW状态了
/**
* 循环1次 进 q = null 的判断 q = new WaitNode();
* 循环2-n次 进 !queued 的判断 queued = 执行
* compareAndSwapObject(this, waitersOffset, q.next = waiters, q)
* 当 FutureTask 的 waiters 没有变化 则 将之前创建的等待节点放到头部 并将 waiters 更新为 q
* 循环第n次,当已经放入队列了,但是任务状态还是没有执行完,则调用LockSupport.park(this)让线程进入等待
*/
else if (q == null) // 等待队列为空,创建一个 等待节点
q = new WaitNode();
else if (!queued) // 将q放到等待队列头部
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 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);
}
总结一下获取任务的流程,当有线程调用get方法的时候,如果任务没有执行完成,判断是否设置超时处理,如果超时了则直接返回状态,否则让调用线程进入等待。
再看看任务是如何完成,并进行通知的,回到刚刚的 ThreadPoolExecutor 看过之前文章的话应该知道任务会被Worker对象执行,worker获取到task之后,会调用其run方法,那我们看看 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 {
// 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);
}
}
可以看到 result = c.call(); 也就是这里真正去执行业务代码,获取Callable返回结果。如果业务执行成功 set(result); 进入 set 方法 然后看到调用的 finishCompletion去唤醒调用get方法而阻塞的线程
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
}