FutureTask功能用法

类结构

源码中详细说明了FutureTask生命周期状态及变化

    /**
* 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
*/
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;

实现细节

Future#get()方法的实现

FutureTask既然实现了Future接口,就先看下Future#get()函数的实现

    /**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
} /**
* 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 (;;) {
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)
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);
}
}

这个awaitDone函数,实现了在Callable对象未complete时当前线程等待的功能。成员变量waiters是一个等待在该FutureTask#get()上的线程的链表,WaitNode有当前Thread的变量

 /** Treiber stack of waiting threads */
private volatile WaitNode waiters;

awaitDone首先将当前线程加入等待队列waiters,然后调用LockSupport#park阻塞自己,等待被唤醒再根据state状态返回,或者过nanos时间后返回。park是“忙碌等待”的一种优化,它不会浪费这么多的时间进行自旋。

可以看到,循环中设置了中断处理逻辑。LockSupport.park()支持中断影响,它不会抛出InterruptedException异常,只是默默的返回。但是,我们可以从Thread.interrupted()等方法获得终端标记。

当执行Callable的异步线程完成task后,会唤醒阻塞在awaitDone上的当前线程,

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()设置结果,并调用finishCompletion()清除和通知waiters上的等待线程。

/**
* 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
}
中断处理代码和time-out时间到的代码中都调用到removeWaiter(WaitNode node)函数,该函数安全的删除waiters链表中的node结点,也就时当当前线程被中断或者time-out时,从等待队列中删除该线程。
看看该算法的实现:
     /**
* 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;
}
}
}

算法有特别的地方,它保证了线程安全,但是没有用任何锁或者CAS操作。waiter链表添加元素只在头部进行,多个线程同时对链表traverse删除结点,会导致一个显式的竞争,即在删除node结点的同时(进入第20行代码后),另外一个线程在删除pre结点,此时会出现这样一种可能,删除pre结点的线程中s(删除结点的后继结点)还指向node,导致node被重新赋值给pred->next,就是node没有被删除。处理的办法时当前线程restart从头开始再删除一遍node(此时结点pre已经被删除,node的前趋结点变成了pre的前趋结点),代码中第22-23行代码,对这种竞争进行检查并处理。除此之外,多个线程同时释放结点,不会产生竞争问题。25-26行代码是删除链表第一个node的处理逻辑。

Future#cancel()方法的实现

参数mayInterruptIfRunning决定,task运行时能否被中断。

    public boolean cancel(boolean mayInterruptIfRunning) {
if (state != NEW)
return false;
if (mayInterruptIfRunning) {
if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
return false;
Thread t = runner;
if (t != null)
t.interrupt();
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
}
else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
return false;
finishCompletion();
return true;
}

Runnable#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);
}
}

run()方法没有显式的中断处理逻辑,他通过state状态来回应cancel()的中断。cancel()提出中断时,将state置为interrupting,此时调用set()和setException()不产生任何效果。

runAndReset()方法,这个函数为那些执行多次且不带返回值的任务设置。

    /**
* Executes the computation without setting its result, and then
* resets this future to initial state, failing to do so if the
* computation encounters an exception or is cancelled. This is
* designed for use with tasks that intrinsically execute more
* than once.
*
* @return true if successfully run and reset
*/
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable<V> c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} 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
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}

总结

FutureTask是通过LockSupport来阻塞线程,唤醒线程。对于多线程访问FeatureTask的 waiters,state,都是采用Unsafe来操作,避免使用锁,改为直接原子操作对应的变量。FeatureTask是一个 非常好的Unsafe和LockSupport例子。


 
 

FutureTask源码阅读的更多相关文章

  1. Java多线程类FutureTask源码阅读以及浅析

    FutureTask是一个具体的实现类,实现了RunnableFuture接口,RunnableFuture分别继承了Runnable和Future接口,因此FutureTask类既可以被线程执行,又 ...

  2. ThreadPoolExecutor 源码阅读

    目录 ThreadPoolExecutor 源码阅读 Executor 框架 Executor ExecutorService AbstractExecutorService 构造器 状态 Worke ...

  3. [源码阅读] 阿里SOFA服务注册中心MetaServer(2)

    [源码阅读] 阿里SOFA服务注册中心MetaServer(2) 目录 [源码阅读] 阿里SOFA服务注册中心MetaServer(2) 0x00 摘要 0x01 MetaServer 注册 1.1 ...

  4. FutureTask源码深度剖析

    FutureTask源码深度剖析 前言 在前面的文章自己动手写FutureTask当中我们已经仔细分析了FutureTask给我们提供的功能,并且深入分析了我们该如何实现它的功能,并且给出了使用Ree ...

  5. 【原】FMDB源码阅读(三)

    [原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...

  6. 【原】FMDB源码阅读(二)

    [原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...

  7. 【原】FMDB源码阅读(一)

    [原]FMDB源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 说实话,之前的SDWebImage和AFNetworking这两个组件我还是使用过的,但是对于 ...

  8. 【原】AFNetworking源码阅读(六)

    [原]AFNetworking源码阅读(六) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这一篇的想讲的,一个就是分析一下AFSecurityPolicy文件,看看AF ...

  9. 【原】AFNetworking源码阅读(五)

    [原]AFNetworking源码阅读(五) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中提及到了Multipart Request的构建方法- [AFHTTP ...

随机推荐

  1. 洛谷P2751 工序安排Job Processing

    题目 任务调度贪心. 需要明确一点,任务调度贪心题,并不是简单地应用排序的贪心,而是动态的运用堆,使每次选择是都能保持局部最优,并更新状态使得下次更新答案可以取到正确的最小值. 这是A过程的解. 然后 ...

  2. StarUML自动生成Java代码

    下载一个starUML 链接:https://pan.baidu.com/s/1pIGNVmhtwBxMrCG9LHdkCQ 提取码:c4i6 复制这段内容后打开百度网盘手机App,操作更方便哦 添加 ...

  3. [WEB安全]PHP伪协议总结

    0x01 简介 首先来看一下有哪些文件包含函数: include.require.include_once.require_once.highlight_file show_source .readf ...

  4. 0915 N校联考

    树上路径(phantasm) 题目背景 Akari是一个普通的初中生. 题目描述 Akari的学校的校门前生长着一排n棵树,从西向东依次编号为1∼n.相邻两棵树间的距离都是1.Akari上课的教学楼恰 ...

  5. Nginx模块说明

    一.Nginx内置模块 -–prefix= #指向安装目录 -–sbin-path #指向(执行)程序文件(nginx) -–conf-path= #指向配置文件(nginx.conf) -–erro ...

  6. ubuntu之路——day10.4 什么是人的表现

    结合吴恩达老师前面的讲解,可以得出一个结论: 在机器学习的早期阶段,传统的机器学习算法在没有赶超人类能力的时候,很难比较这些经典算法的好坏.也许在不同的数据场景下,不同的ML算法有着不同的表现. 但是 ...

  7. ubuntu之路——day1(一点十五分 MMP终于把显卡装好了)

    因为要上手深度学习的原因,购置了一台RTX2080TI+ubuntu18.04的机器 例行两条命令 sudo apt-get update sudo apt-get upgrade 开启巨坑第一天,以 ...

  8. 三大框架 之 Struts2

    目录 Struts2 Struts2简介 Struts2框架的作用 常见web层的框架 web框架特点 Struts2基本使用 Struts2执行流程 Struts2配置 struts2的加载顺序 P ...

  9. TL-WR941N路由器刷DD-WRT和OPENWRT教程及使用花生壳

    今天没事做,于是决定把自己的TL-WR941N路由器刷成OPENWRT系统的.虽然说没买小米路由,但是刷成OPENWRT系统的话还是能增强不少的功能.下面写出经过一下午折腾的详细安装步骤,同样适用于其 ...

  10. npm install 时 No matching version found for react-flow-design@1.1.14

    执行 npm install时报错如下: 4017 silly pacote range manifest for react-highcharts@^16.0.2 fetched in 19ms40 ...