JDK的Future源码解析
1.Callable/Runnable
java.lang.Runnable接口只声明了一个run方法:
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
java.util.concurrent.Callable只声明一个Call()方法:
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
这是个泛型接口,call函数返回的类型就是传进来的v类型;
Callable一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本,看java.util.concurrent.ExecutorService源码:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
2 Future接口
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
java.util.concurrent.Future接口:
* @see FutureTask
* @see Executor
* @since 1.5
* @author Doug Lea
* @param <V> The result type returned by this Future's {@code get} method
*/
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
在Future接口中声明了5个方法:
cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务。如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
isCancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。
isDone方法表示任务是否已经完成,若任务完成,则返回true;
get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;
get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
Future提供了三种功能:
1)判断任务是否完成;
2)能够中断任务;
3)能够获取任务执行结果。
3 FutureTask
3.1 FutureTask类
FutureTask类实现了RunnableFuture接口:
public class FutureTask<V> implements RunnableFuture<V> {
而RunnableFuture继承了Runnable接口和Future接口:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
所以FutureTask既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
3.2 state字段
volatile修饰的state字段;
/**
* 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;
3.3 其他变量
runner和waiters为volatile类型
/** 任务 */
private Callable<V> callable;
/** 储存结果*/
private Object outcome; // non-volatile, protected by state reads/writes
/** 执行任务的线程*/
private volatile Thread runner;
/** get方法阻塞的线程队列 */
private volatile WaitNode waiters;
3.4 构造器
FutureTask有2个构造器:
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
}
这两个构造函数区别在于,如果使用第一个构造函数最后获取线程实行结果就是callable的执行的返回结果;而如果使用第二个构造函数那么最后获取线程实行结果就是参数中的result,接下来让我们看一下FutureTask的run方法
3.5 CAS工具初始化
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
3.6 get方法的等待队列
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
3.7 run方法
public void run() {
//如果状态不是new,或者runner旧值不为null,就结束
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);
}
//如果正常完成,就设置result和state
if (ran)
set(result);
}
} finally {
// 设置runner为null,阻止结束后再调用run()方法
runner = null;
// 重读state,防止中断泄露
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
其中,catch语句中的setException(ex)如下:
//发生异常时设置state和outcome
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // 唤醒get()方法阻塞的线程
finishCompletion();
}
}
而正常完成时,set(result);方法如下:
//正常完成时,设置state和outcome
protected void set(V v) {
//正常完成时,NEW->COMPLETING->NORMAL
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
// 唤醒get方法阻塞的线程
finishCompletion();
}
}
而唤醒get方法阻塞的线程方法如下:
//移除并唤醒所有等待的线程,调用done,并清空callable
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
}
重点看一下handlePossibleCancellationInterrupt方法, 这个方法是自旋等待state变为INTERRUPTED(对应cancel方法的结束),即等待中断的结束。
private void handlePossibleCancellationInterrupt(int s) {
// It is possible for our interrupter to stall before getting a
// chance to interrupt us. Let's spin-wait patiently.
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
// assert state == INTERRUPTED;
// We want to clear any interrupt we may have received from
// cancel(true). However, it is permissible to use interrupts
// as an independent mechanism for a task to communicate with
// its caller, and there is no way to clear only the
// cancellation interrupt.
//
// Thread.interrupted();
}
3.8 get方法解析
get()方法有2种:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//阻塞直到任务完成
s = awaitDone(false, 0L);
return report(s);
}
/**
* @throws CancellationException {@inheritDoc}
*/
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);
}
new状态的Futuretask的get将会阻塞。
get() 方法中涉及到 awaitDone 方法, 将awaitDone的运行结果赋值给state, 最后report方法根据state值进行返回相应的值, 而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 (;;) {
// 重置中断状态并返回之前的中断状态
if (Thread.interrupted()) {
//如果已经被中断过,则移除q
removeWaiter(q);
//并抛出中断异常
throw new InterruptedException();
}
int s = state;
//如果已经成为终止状态,则返回state的值
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//如果设置结果,马上就能完成,则自旋等待
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//为NEW,正在执行或者还没开始,就构建新节点给q
else if (q == null)
q = new WaitNode();
//判断是否入队,新建节点一般在下一次循环入队阻塞
else if (!queued)
//没有入队则入队
//设置q.next=waiters,然后再将waiter CAS设置为q
queued = UNSAFE.compareAndSwapObject(this,waitersOffset, q.next = waiters, q);
//如果有超时限制,判断是否超时
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
//超时则移除节点
removeWaiter(q);
return state;
}
阻塞get()方法的线程,有超时限制
LockSupport.parkNanos(this, nanos);
}
//已经入队则继续阻塞
else
//阻塞get()方法的线程,无超时限制
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;
}
}
}