FutureTask
ThreadPoolExecutor线程池submit提交任务返回一个Future对象,实际是FutureTask
Future 接口的get方法具有阻塞特性
我们从源码角度来了解下
任务状态:
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; //任务线程已中断
WaiteNode
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
WaitNode是一个链表结构,多个线程调用Future Get方法时都会阻塞,添加到这个等待列表
get方法:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
获取任务状态,如果任务未完成,调用awaitDone方法
任务完成(包括取消) 调用report方法
report方法:
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);
}
任务正常处理完返回处理结果(outcome )
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()) {// @1
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {//@2
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();//@3
else if (q == null)
q = new WaitNode();//@4
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q); //@5
else if (timed) {// @6
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else //@7
LockSupport.park(this);
}
}
现在来分析下这块代码
- 处理线程中断,从等待队列中删除当前线程
- 任务已完成直接返回
- COMPLETING 状态 线程让出一定CPU时间
- 创建一个WaitNode
- 将刚创建的WaitNode添加到等待列表中(这里注意下compareAndSwapObject方法,有4个参数分别是对象,对象要比较的属性的偏移量,期望值 expec,要更新成为的值 update,如果对象的属性值与期望值expect一样,则更新属性的值为update并返回true
)waitersOffset就是FutureTask waiters的地址,所以,这个方法一般都是成功的,触发别的线程get方法先改掉了,这里形成的就是一个链表 - 如果有超时设置锁定一段时间
- 锁定一段时间
锁定后当前线程就会阻塞,等同FutureTask任务完成后,唤醒线程
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);
}
}
成功执行完后 调用set方法将结果赋值给outcome变量,解除阻塞后get方法就能获取到值了
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
CAS改变任务状态
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
}
这里遍历队列,调用LockSupport.unpark 解除阻塞的线程