java并发编程之FutureTask源码

「本文已参与好文召集令活动,点击查看:后端、大前端双赛道投稿,2万元奖池等你挑战!

前言

说到FutureTask就不得不说到CallablFuture;其中Callabl是一个接口,用来定义任务,且有返回值的地方,且可以有返回值。Future是用来获取Callabl执行结果的。本篇笔记主要写FutureTask源码的。

正文

1
2
3
4
java复制代码
public class FutureTask<V> implements RunnableFuture<V>{}

public interface RunnableFuture<V> extends Runnable, Future<V> {}

FutureTask实现了RunnableFuture接口。而RunnableFuture接口又继承了 Runnable接口和Future接口。

所以,FutureTask可以作为Runnable参数,传入Thread,然后启动线程执行任务。

常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码
/** The underlying callable; nulled out after running */
private Callable<V> callable; // 被执行的任务

/** The result to return or exception to throw from get() */
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; // 等待节点,用于存储等待结果的线程,链表结构

在FutureTask中定义了一个state,标记任务的执行状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
java复制代码
/*
* 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; // 中断

其中状态之间的转换也在注释中已经说明。

构造方法

1
2
3
4
5
6
7
8
9
10
11
12
java复制代码
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
}

构造方法有两个,都是将状态置为NEW;
其中接收Runnable参数的构造方法需要传入固定值,且使用Executors.callable方法将Runnableresult转为callable,该方法中用到了适配器模式。感兴趣的可以进源码去看看。

run方法

run方法是线程直接调用的地方。其实最根本的原理和Runnable的执行是一样的,只是这里多进行了一次包装,对执行结果进行了处理。

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
java复制代码
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);
}
}

run方法看起来还是比较简单,就是执行call方法,然后保存执行结果。

这里主要看两个方法,setException和set

setException

这个方法是执行任务出错后调用的方法,其中将错误信息作为参数。下面来看看源码:

1
2
3
4
5
6
7
8
java复制代码
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}

源码也比较简单:

  1. CASstateNEW转为COMPLETING
  2. 将错误信息赋予outcome
  3. state转为EXCEPTIONAL
  4. 执行finishCompletion方法

set方法

这个方法是执行任务成功后调用的方法,将执行结果作为参数传入该方法。源码如下:

1
2
3
4
5
6
7
8
java复制代码
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}

流程和setException方法是一样的,唯一的区别就是第三步是将state转换为NORMAL

finishCompletion

这个方法是在setsetException中都调用了的。注释说明的是:移除所有等待线程,并向线程发送信号,执行done()方法,置callablenull

下面看看源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
java复制代码
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) { // 循环存储线程的链表
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { // CAS修改waiters的值为null
for (;;) {
Thread t = q.thread; // 获取线程
if (t != null) {
q.thread = null; // 置为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
}

源码也比较简单,就是for循环遍历等待线程的链表,然后通过LockSupport.unpark来通知线程。这里主要注意LockSupport.unpark的使用和原理。

其实线程执行任务的大概流程就是:

  1. 线程执行任务
  2. 判断执行结果,并保存结果(执行失败还是成功)
  3. 修改状态和保存结果信息
  4. 挨个通知等待中的线程(LockSupport.unpark

isCancelled

根据状态判断是否被取消掉

1
2
3
4
java复制代码
public boolean isCancelled() {
return state >= CANCELLED;
}

isDone

判断线程是否完成

1
2
3
4
java复制代码
public boolean isDone() {
return state != NEW;
}

cancel

取消任务

源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
java复制代码
public boolean cancel(boolean mayInterruptIfRunning) {
// CAS修改状态,根据mayInterruptIfRunning判断修改为INTERRUPTING还是CANCELLED
// 修改失败就返回false,修改成功则进行下一步
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;
}

源码也比较简单,主要还是看mayInterruptIfRunning参数,这个参数就是是否取消正在执行中的任务。为true的话就使用Threadinterrupt来取消任务的执行。最后通知等待线程取消等待。

get

这个名字有两个方法,一个是一直等待,一个是等待有限时长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
java复制代码
// 这个方法是一直处于等待中,直到有结果为止
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING) // 如果状态在运行中或NEW,则等待(调用awaitDone)
s = awaitDone(false, 0L);
return report(s);
}
// 这个是等待有限时长
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);
}

大概流程就是:

  1. 判断状态,是否调用awaitDone
  2. 根据状态返回结果

两个方法都差不多,都是调用awaitDone方法,只是参数不一样。

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
java复制代码
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;
// 任务执行完成,返回状态码
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null) //构建节点
q = new WaitNode();
else if (!queued) // CAS修改waiters(头插法)
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);
}
}

这个方法主要就三点:

  1. 用当前线程构建WaitNode,然后使用CASWaitNode加入waiters中,waiters就是一个链表
  2. 使用LockSupport来阻塞线程(有限时长或无限时长)
  3. 成功则返回状态码

report

这个方法也比较简单

1
2
3
4
5
6
7
8
9
java复制代码
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); // 执行错误返回
}

最后

总结

整体来说,源代码是比较简单的。思想上来说,FutureTask就是一个中间类,实质可以看成是一个Runnable,其内部对Callable进行了包装(重写run方法),然后使用LockSupport来对线程阻塞和通知线程,使其达到等待任务执行完成,且获取结果的效果。

FutureTask中的state(状态),从执行任务的角度(callable)来看,严格意义上来说状态并没有完全一一对应,比如NEW状态,有可能任务已经完成,或者执行出错(只是结果还未保存到共享变量(outcome)中),这一点可以在run方法中看出,状态的修改是在Callablecall方法执行过后。如果FutureTask整体的角度来看就不一样了。

Callable的启动有两种方式:

第一种:将Callable作为参数,构建FutureTask,然后将FutureTask作为参数,创建Thread实例,然后启动start

第二种:直接将Callable放入线程池的submit方法中,然后返回FutureTask。线程池的原理和第一种方式是一样的,线程池是在submit方法中实现的第一种的步骤。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%