类注释
我们思考一下什么是FutureTask呢?我们什么时候会用FutureTask?
A cancellable asynchronous computation.可以取消的异步计算.
This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation.. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset).
Future接口
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;
}
类结构

状态
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;
注意state是volatile的.
核心变量
//待返回值任务的占位符.
private Callable<V> callable;
//结果.
private Object outcome;
//执行任务的线程.如果当前线程不是runner,直接返回.
private volatile Thread runner;
//等待的节点.什么时候会等待.awaitDone里会添加.
private volatile WaitNode waiters;
先看看核心的run方法.
public void run() {
//状态不是New,或者状态是New的情况下,runner不是当前的线程.直接返回
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 = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
compareAndSwapObject的用法
方法签名
//obj :包含要修改的字段对象;
//offset :字段在对象内的偏移量;
//expect : 字段的期望值;
//update :如果该字段的值等于字段的期望值,用于更新字段的新值;
public native boolean compareAndSwapObject(Object obj, long offset, Object expect, Object update);
set解密
protected void set(V v) {
//cas成功
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//赋值给结果
outcome = v;
//改变状态
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//完成
finishCompletion();
}
}
//Removes and signals all waiting threads, invokes done(), and nulls out 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
}
下面看看get()的流程吧
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
带超时的get.
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
//状态必须要小于等于COMPLETING 且awaitDone
if (s <= COMPLETING &&
//等待完成
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
下面看看awaitDone吧.
awaitDone里除了异常场景是不会删除waitNode的.因为这个清理的任务由set来做.
1.get的时候如果set完成了,那么就没有waitNode.
2.get的时候如果set没有完成,那么处理成功的时候,set自动清除.
//返回状态值.
private int awaitDone(boolean timed, long nanos) throws InterruptedException {
//判断超时截止时间
final long deadline = timed ? System.nanoTime() + nanos : 0L;
//初始化一个node.
WaitNode q = null;
//
boolean queued = false;
//必然有死循环
for (;;) {
//判断线程是否被打断.
if (Thread.interrupted()) {
//删除waiter
removeWaiter(q);
throw new InterruptedException();
}
//
int s = state;
if (s > COMPLETING) {
if (q != null)
//
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
//A hint to the scheduler that the current thread is willing to yield its current use of a processor. The
//scheduler is free to ignore this hint.
Thread.yield();
else if (q == null)
//新建一个waitNode
q = new WaitNode();
//如果没有入队列
else if (!queued)
//cas入队列.
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q);
else if (timed) {
//小于0就说明已经超时了.
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
小知识点
LockSupport.park(this);
扩展阅读
WaitNode
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
FutureTask的源码其实很简单,现在我们来反思一下这个类的设计吧.
这个类的代码写的确实优雅.抽象的也很到位,就是一个可以取消的异步的执行任务.不需要去管任务的提交,
线程的分配.
但是这个类缺少了任务完成主动通知,得要直接傻傻的get等待.那么netty是怎么优化的呢?CompleteFuture又做了什么?CompleteFuture的1.9又做了哪些升级呢?
任务是如何被提交的?
public <T> Future<T> submit(Runnable task, T result) {
//空指针校验.
if (task == null) throw new NullPointerException();
//new一个任务.
RunnableFuture<T> ftask = newTaskFor(task, result);
//执行.
execute(ftask);
//
return ftask;
}
//新建一个FutureTask
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
线程池的execute.
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//放入到workerQueue里.
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
然后看看Worker里的run方法
public void run() {
runWorker(this);
}
worker是如何被触发的?
这里先不细说,线程池那边会单独的写.
addWorker里如果worker添加成功了,然后会 t.start();
final Thread t = w.thread;
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//获取任务.多个线程共享一个任务队列.
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
//执行任务.
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
所以线程池里的线程就会触发futureTask.
cancel
public boolean cancel(boolean mayInterruptIfRunning) {
//状态校验.state=new且cas成功才能cancel.
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;
}
private void finishCompletion() {
// assert state > COMPLETING;
//遍历等待节点
for (WaitNode q; (q = waiters) != null;) {
//cas
if (WAITERS.weakCompareAndSet(this, 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状态的流转
1.什么时候变成COMPLETING
set里
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
}
setException里
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
}
2.什么时候变成NORMAL,还是在set里
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
//outcome设置后
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
3.什么时候变成EXCEPTIONAL
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
//这里
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
4.什么时候变成CANCELLED.INTERRUPTING.
没有开始叫取消,已经开始的叫打断.
cancel里,mayInterruptIfRunning必须等于false.才会cas设置成CANCELLED
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
5.什么时候INTERRUPTED.
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;
}
小知识.
putOrderedInt