FutureTask源码解析

FutureTask源码解析

FutureTask是Future的实现类,它实现了RunnableFuture接口,而RunnableFutrue又继承了Runnable和Future接口。

FutureTask可以拆分为Future和Task,Future对应Future接口的相关功能,Task对应Runnabl接口相关功能。因此,可以把FutureTask当做是一个任务,一个简单的Runnable对象。

类图

FutureTask的类图如下所示:

FutureTask实现了RunnableFuture接口

1
public class FutureTask<V> implements RunnableFuture<V> 

RunnableFuture接口只是继承了Runnable和Future接口,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* A {@link Future} that is {@link Runnable}. Successful execution of
* the {@code run} method causes completion of the {@code Future}
* and allows access to its results.
* @see FutureTask
* @see Executor
* @since 1.6
* @author Doug Lea
* @param <V> The result type returned by this Future's {@code get} method
*/
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}

主要属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* The run state of this task, initially NEW. The run state
* transitions to a terminal state only in methods set,
* setException, and cancel. During completion, state may take on
* transient values of COMPLETING (while outcome is being set) or
* INTERRUPTING (only while interrupting the runner to satisfy a
* cancel(true)). Transitions from these intermediate to final
* states use cheaper ordered/lazy writes because values are unique
* and cannot be further modified.
*
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
// 当前任务的状态,初始化为NEW,状态只会在set,setException和cancel方法中被设置
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;

/** The underlying callable; nulled out after running */
// 运行的任务,完成之后被设置为null
private Callable<V> callable;
/** The result to return or exception to throw from get() */
// 包装返回结果或者异常,没有被volatile修饰,状态保护读写安全
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
// 运行的线程
private volatile Thread runner;
/** Treiber stack of waiting threads */
// 单链表,是一个线程的栈的结构
private volatile WaitNode waiters;

主要方法

有参构造函数-指定运行任务

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Callable}.
*
* @param callable the callable task
* @throws NullPointerException if the callable is null
*/
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}

任务不能为null,状态设置为NEW

有参构造函数-指定任务和成功返回结果

传入要执行的任务和任务执行成功后的结果。将Runnable对象封装为Callable对象。任务执行成功,或者成功结束后,返回传入的result,如果不需要返回结果的话,可以直接传入null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
* {@code Future<?> f = new FutureTask<Void>(runnable, null)}
* @throws NullPointerException if the runnable is null
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}

isCanceled

任务是否取消。状态如果大于等于CANCELLED,就表示已经取消

1
2
3
public boolean isCancelled() {
return state >= CANCELLED;
}

isDone

任务状态不为NEW,就表示已经完成

1
2
3
public boolean isDone() {
return state != NEW;
}

cancel

取消当前正在执行的任务。

如果当前任务状态不为NEW,或者设置状态INTERRUPTING(mayInterruptIfRunning = true)或CANCELLED(mayInterruptIfRunning=false)失败,返回false

如果mayInterruptIfRunning设置为true,那么就中断当前线程,在finally中会设置线程的状态为INTERRUPTED

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}

finishCompletion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Removes and signals all waiting threads, invokes done(), and
* nulls out callable.
*/
// 移除并激活所有的等待线程,调用done方法,并设置callable为false
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
}

done

done方法在FutureTask中是一个空实现,使用FutureTask的时候可以重写这个方法

1
2
3
4
5
6
7
8
9
10
/**
* Protected method invoked when this task transitions to state
* {@code isDone} (whether normally or via cancellation). The
* default implementation does nothing. Subclasses may override
* this method to invoke completion callbacks or perform
* bookkeeping. Note that you can query status inside the
* implementation of this method to determine whether this task
* has been cancelled.
*/
protected void done() { }

get

1
2
3
4
5
6
7
8
public V get() throws InterruptedException, ExecutionException {
int s = state;
// 如果当前任务还没有完成,等待.没有超时时间,如果任务一直不完成,一直等待
if (s <= COMPLETING)
s = awaitDone(false, 0L);
//
return report(s);
}

awaitDone

等待任务完成或者放弃或者中断或者超时。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Awaits completion or aborts on interrupt or timeout.
*
* @param timed true if use timed waits
* @param nanos time to wait, if timed
* @return state upon completion
*/
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
// 如果当前线程已经被中断了,从waiter中移除,并抛出中断异常,如果q为null的话,方法直接返回
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}

int s = state;
// 再次检查,此时任务可能已经完成
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
// 如果任务状态为COMPLETING,可以参考上面的任务状态解释,让出cpu
// 表示任务已经结束但是任务执行线程还没来得及给outcome赋值
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
// q == null,说明是来等待任务完成的,需要新建一个节点
q = new WaitNode();
else if (!queued)
// 节点新建完成后,在下一个循环将原等待队列挂在到当前节点之后
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) { // 如果设置了超时
nanos = deadline - System.nanoTime();
// 如果已经超时
if (nanos <= 0L) {
// 从等待队列中移除
removeWaiter(q);
// 返回当前状态
return state;
}
// 阻塞当前线程nanos纳秒
LockSupport.parkNanos(this, nanos);
}
else
// 无限期阻塞当前线程
LockSupport.park(this);
}
}

removeWaiter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Tries to unlink a timed-out or interrupted wait node to avoid
* accumulating garbage. Internal nodes are simply unspliced
* without CAS since it is harmless if they are traversed anyway
* by releasers. To avoid effects of unsplicing from already
* removed nodes, the list is retraversed in case of an apparent
* race. This is slow when there are a lot of nodes, but we don't
* expect lists to be long enough to outweigh higher-overhead
* schemes.
*/
// 从等待队列中删除超时或者已经中断的节点,便于垃圾回收
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;
}
}
}

report

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Returns result or throws exception for completed task.
*
* @param s completed state value
*/
@SuppressWarnings("unchecked")
// 根据状态从outcome中获得结果
private V report(int s) throws ExecutionException {
Object x = outcome;
// 如果状态为normal,说明任务正常执行完成
if (s == NORMAL)
return (V)x;
// 如果状态值大于等于CANCELLED,说明任务被取消了
if (s >= CANCELLED)
throw new CancellationException();
// 其他状态,直接抛异常
throw new ExecutionException((Throwable)x);
}

set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon successful completion of the computation.
*
* @param v the value
*/
// FutureTask的任务只会set一次,因为状态不可能从中间状态或者终结状态变为NEW
// 将结果set给outcome之后,任务的状态才会变为NORMAL,COMPLETING只是一个中间状态
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}

setException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Causes this future to report an {@link ExecutionException}
* with the given throwable as its cause, unless this future has
* already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon failure of the computation.
*
* @param t the cause of failure
*/
// 设置任务的异常信息。也只会设置一次。
// 也只有在设置完outcome之后,任务的状态才会变为EXCEPTIONAL
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}

run

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 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);
}
}

handlePossibleCancellationInterrupt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Ensures that any interrupt from a possible cancel(true) is only
* delivered to a task while in run or runAndReset.
*/
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.
// 如果当前状态是INTERRUPTING
if (s == INTERRUPTING)
// 一直自旋,直到state为INTERRUPTING为止,让出CPU
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();
}

run方法重点做了以下几件事:

  1. 将runner属性设置成当前正在执行run方法的线程
  2. 调用callable成员变量的call方法来执行任务
  3. 设置执行结果outcome, 如果执行成功, 则outcome保存的就是执行结果;如果执行过程中发生了异常, 则outcome中保存的就是异常,设置结果之前,先将state状态设为中间态
  4. 对outcome的赋值完成后,设置state状态为终止态(NORMAL或者EXCEPTIONAL)
  5. 唤醒栈中所有等待的线程
  6. 善后清理(waiters, callable,runner设为null)
  7. 检查是否有遗漏的中断,如果有,等待中断状态完成。
0%