jdk1.8 J.U.C之FutureTask实现机制分析
我画了一张关于FutureTask的类图,主要包括FutureTask的几个重要的函数和字段,还有它和父类的关系。

根据上面图我们可以清晰的看出FutureTask的继承关系。FutureTask继承一个最重要的类是Future,有几个比较重要的方法get,cancel,isCancelled等。FutureTask是为了弥补Thread的不足而设计的,它可以让程序员准确地知道线程什么时候执行完成并获得到线程执行完成后返回的结果(如果有需要)。FutureTask是一种可以取消的异步的计算任务。它的计算是通过Callable实现的,它等价于可以携带结果的Runnable,并且有三个状态:等待、运行和完成。完成包括所有计算以任意的方式结束,包括正常结束、取消和异常。
```java
public class FutureTaskTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
FutureTask futureTask = new FutureTask(new Callable() {
public Integer call() throws Exception {
System.out.println("执行一个比较耗时的任务");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i System.out.println("主线程....");
try {
futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有的任务执行完毕....");
}
}
从上面的例子中我们可以看到FutureTask在执行异步的时候是需要依托线程池的。也就是调用 Executors.newCachedThreadPool(),submit是把futureTask这个Task交给线程池,我们可以看下AbstractExecutorService的submit:
```java
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
然后执行execute,这个方法是Executor接口中的唯一方法
public interface Executor {
void execute(Runnable command);
}
方法是实现是在ThreadPollExecutor,这个方法主要是从线程池中获取一个线程来执行call任务,具体的逻辑我暂时还不是很清楚,因为这块源码我还没有研究过,有空的时候再研究下到时候更新下这篇文章。
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
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);
}
下面是FutureTask的源码分析,futureTask初始化
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
state是一个volatile的变量,用线程的状态
/**
* 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;
注释已经写得很清楚了,初始化的时候是NEW,Callable的call执行完就变为COMPLETING没有异常就再改为 NORMAL,否则就是EXCEPTIONAL
当线程开始执行的时候会先执行run函数。那么一般的我们的task会在初始化的时候new一个Callable对象,并重写call函数。所以在run的时候是会执行call这个函数。看下call代码就一目了然了。
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);
}
}
所以当call还没执行完我们的主线程会继续执行直到遇到get方法。get会执行阻塞,那么call什么时候才会被唤醒呢,这个就需要操作系统的支持了,这里的处理方式跟AQS一样是托管给操作系统,先把线程挂起,等待操作系统唤醒,那么get这个方法到底做了什么处理呢?
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
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);
}
}
这个waitDone最重要的职能有两点一个是把当前线程的WaitNode赋值给waiters,通过CAS。二是把这个线程阻塞,通过LockSupport.park,直到call执行完毕,那么run就会执行set方法,set主要是修改state的状态:
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
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
}
有意思的是FutureTask预留了一个done函数给它的子类用,有需要的开发者可以对这个函数进行重写。
protected void done() {
参考:
http://ifeve.com/abstractqueuedsynchronizer-use/#more-18899
jdk1.8 J.U.C之FutureTask实现机制分析的更多相关文章
- 【并发编程】【JDK源码】J.U.C--组件FutureTask、ForkJoin、BlockingQueue
原文:慕课网实战·高并发探索(十三):并发容器J.U.C -- 组件FutureTask.ForkJoin.BlockingQueue FutureTask FutureTask是J.U.C中的类,是 ...
- java中Future与FutureTask使用与分析
Future与FutureTask都是用于获取线程执行的返回结果.下面我们就对两者之间的关系与使用进行一个大致的介绍与分析 一.Future与FutureTask介绍: Future位于java.ut ...
- FutureTask 源码分析
FutureTask 源码分析,这个类的原理与我分析android当中的FutureTask类差不多[http://www.cnblogs.com/daxin/p/3802392.html] publ ...
- 并发容器J.U.C --组件FutureTask、ForkJoin、BlockingQueue
FutureTask FutureTask是J.U.C中的类,是一个可删除的异步计算类.这个类提供了Future接口的的基本实现,使用相关方法启动和取消计算,查询计算是否完成,并检索计算结果.只有在计 ...
- 一文带你了解J.U.C的FutureTask、Fork/Join框架和BlockingQueue
摘要: J.U.C是Java并发编程中非常重要的工具包,今天,我们就来着重讲讲J.U.C里面的FutureTask.Fork/Join框架和BlockingQueue. 本文分享自华为云社区<[ ...
- Java并发编程笔记之FutureTask源码分析
FutureTask可用于异步获取执行结果或取消执行任务的场景.通过传入Runnable或者Callable的任务给FutureTask,直接调用其run方法或者放入线程池执行,之后可以在外部通过Fu ...
- 并发编程—— FutureTask 源码分析
1. 前言 当我们在 Java 中使用异步编程的时候,大部分时候,我们都会使用 Future,并且使用线程池的 submit 方法提交一个 Callable 对象.然后调用 Future 的 get ...
- FutureTask源码分析
1. 常量和变量 private volatile int state; // 任务状态 private static final int NEW = 0; private static final ...
- 并发编程-Future+callable+FutureTask 闭锁机制
项目中经常有些任务需要异步(提交到线程池中)去执行,而主线程往往需要知道异步执行产生的结果,这时我们要怎么做呢?用runnable是无法实现的,我们需要用callable实现. FutureTask ...
随机推荐
- [原创]HierarchyView的实现原理和Android设备无法使用HierarchyView的解决方法
最近在看一个老外写的东西,发现里面有个类,使用这个类可以让任何设备使用HierarchyView. 众所周知,市面上卖的Android设备,一般都不能使用HierarchyView,所以借此机会,了解 ...
- CSS - Tooltip-arrow 绘制三角形
问题:纯CSS实现bubble的三角形部分 方法:使用border来绘制三角形:例如 .trangle { ; border-color: transparent; border-style: sol ...
- 配置ini指定eclipse启动JDK版
eclipse mars1 需要JDK 1.7+ 解决方案: 改eclipse.ini配置文件 -startupplugins/org.eclipse.equinox.launcher_1.3.100 ...
- BugFixed
- C primer plus 练习题 第七章
1. #include <stdio.h> #define SPACE ' ' #define NEWLINE '\n' int main() { int spaces,newlines, ...
- 【Xamarin报错】 COMPILETODALVIK : UNEXPECTED TOP-LEVEL error java.lang.OutOfMemoryError: Java heap space
Xamarin Android 编译报错: COMPILETODALVIK : UNEXPECTED TOP-LEVEL error java.lang.OutOfMemoryError: Java ...
- 电商O2O-11种最佳运营模式
免费模式,是在这种矛盾下应运而生的新型模式.免费模式在未来的几年中,将会不断的渗透到各个行业中,这不单单是加速了行业内部的洗牌速度,更是加速了行业之间的洗牌速度. 未来,免费模式会让行业之间的界限变得 ...
- Changing Project Binding to Surround SCM Integration Provider with Visual Studio 2010
Changing Project Binding to Surround SCM Integration Provider with Visual Studio 2010 Sarah Wigser t ...
- 12306外包给阿里巴巴/IBM到底是否可行?
春运开始以后 12306 免不了要罢工几次,毕竟人民群众买票回家的热情实在是高涨,12306 很难承受如此大的压力.每次 12306 网站罢工以后都会有人忍不住对其进行吐槽,而还有人认为如果把 123 ...
- swift也开源了.
swift也开源了 微软好多也开源. 这世界都开源了 你还等啥. 是因为 B2D 模式吗. 开发者人数众多, 足可以养活一个公司了. 有的叫生态圈.