java future 源码,读FutureTask源码
class="java">
//一个可以异步返回计算的结果
//它同时实现了Future和Runnable
//先看构造函数
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
//运行runnable并返回给定的result
public FutureTask(Runnable runnable, V result) {
//适配器模式转化runnable接口
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public static Callable callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter(task, result);
}
//适配器模式转化runnable接口
static final class RunnableAdapter implements Callable {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
public void run() {
//如果state不等于0或者设置当前已经被其他线程占用了直接返回。
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable 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 = null;
int s = state;
//如果被取消了
if (s >= INTERRUPTING)
//让出执行权
handlePossibleCancellationInterrupt(s);
}
}
//设定指定值
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() {
//释放所有等待线程
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
}
private void handlePossibleCancellationInterrupt(int s) {
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
}
protected void done() { }
//获取结果
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();
//超时删除q
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
//挂起当前线程
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
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;
//到这里说明q.thread==null,q是需要删除的节点。
else if (pred != null) {
//修改上一个节点的next
pred.next = s;
//上一个节点被删了,重新循环。
if (pred.thread == null)
continue retry;
}
//走到这里说明第一个节点就是被删除的节点
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
//设置失败重新循环
continue retry;
}
break;
}
}
}
//获取值
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);
}
//在一定时间内等待获取结果超时抛出异常
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);
}
//任务是否取消
public boolean isCancelled() {
return state >= CANCELLED;
}
//任务是否完成
public boolean isDone() {
return state != NEW;
}
//试图取消任务的执行
public boolean cancel(boolean mayInterruptIfRunning) {
//任务已经开始直接返回false
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;
}
//将结果设置为异常
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
//执行计算但不设置结果执行完后重置
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} finally {
runner = null;
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}
java future 源码,读FutureTask源码相关推荐
- JDK源码分析 FutureTask源码分析
文章目录 前言 一.Callable接口 二.Future接口 三.FutureTask源码分析 3.1 Future继承结构图 3.2 参数介绍 3.3 构造函数 3.4. FutureTask的A ...
- Java并发编程笔记之FutureTask源码分析
FutureTask可用于异步获取执行结果或取消执行任务的场景.通过传入Runnable或者Callable的任务给FutureTask,直接调用其run方法或者放入线程池执行,之后可以在外部通过Fu ...
- java futuretask 源码解析_Java异步编程——深入源码分析FutureTask
Java的异步编程是一项非常常用的多线程技术. 之前通过源码详细分析了ThreadPoolExecutor<你真的懂ThreadPoolExecutor线程池技术吗?看了源码你会有全新的认识&g ...
- Java多线程类FutureTask源码阅读以及浅析
FutureTask是一个具体的实现类,实现了RunnableFuture接口,RunnableFuture分别继承了Runnable和Future接口,因此FutureTask类既可以被线程执行,又 ...
- Java并发编程之FutureTask源码解析
上次总结一下AQS的一些相关知识,这次总结了一下FutureTask的东西,相对于AQS来说简单好多呀 之前提到过一个LockSupport的工具类,也了解一下这个工具类的用法,这里也巩固一下吧 /* ...
- java 事件分发机制_读Android源码之事件分发机制最全总结
原标题:读Android源码之事件分发机制最全总结 本文源码来自andorid sdk 22,不同版本会有细微差别,但核心机制是一致的 一.概述 事件分发有多种类型, 本文主要介绍Touch相关的事件 ...
- FutureTask源码解析(2)——深入理解FutureTask 1
Future和Task 在深入分析源码之前,我们再来拎一下FutureTask到底是干嘛的.人如其名,FutureTask包含了Future和Task两部分. FutureTask实现了Runnabl ...
- futuretask使用_JDK源码分析-FutureTask
1. 概述 FutureTask 是一个可取消的.异步执行任务的类,它的继承结构如下: 它实现了 RunnableFuture 接口,而该接口又继承了 Runnable 接口和 Future 接口,因 ...
- 源码读不会,小白两行泪!
作者:青石路 来源:https://www.cnblogs.com/youzhibing/p/9553752.html 读源码的经历 刚参加工作那会,没想过去读源码,更没想过去改框架的源码:总想着别人 ...
最新文章
- 分享一波 ZooKeeper 面试题
- php自动到某个时间提醒,2周后,php脚本cron作业将提醒消息发送到特定的电子邮件地址...
- 机器人“快递小哥”上岗了!京东配送机器人编队长沙亮相
- CtStatement
- oracle 字符串转为正数用 to_number()……
- JavaScript通过RegExp实现客户端验证
- 【Linux基础】Linux的5种IO模型详解
- 前端学习(3302):类组件父组件和子组件createRef
- Thrift 教程 开发 笔记 原理 资料 使用 范例 示例 应用
- 普林斯顿校长2018演讲:读书无用是最大的谎言
- JAVA中运行看不见窗口_eclipse中已经把窗口设置为可视,为什么运行 时还是看不到窗口?...
- 硬核干货来啦:Js数组去重,赶快收藏吧
- Python_随笔笔记_Python基础1
- typora插入文件到服务器,写作神器Typora入门指南
- 【CVPR 2021】Revisiting Knowledge Distillation: An Inheritance and Exploration Framework
- 数学中的哈斯图如何构造?附实例
- 看steam教育之风带来创新与变革
- 搭建图片网站:通过cpolar发布图片网站 3/3
- Java Web视频(2013)
- 指数为负数的幂函数 c语言,C语言:求幂函数和指数函数的方法