FutureTask相关
- 上周因为项目中的线程池参数设置的不合理,引发了一些问题,看了下代码,发现对JUC中的一些概念需要再清晰些。
Runnable
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
- Runable是一个interface,定义了run()方法,The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread。如果想在其他线程中执行你的task,需要实现这个接口。
Callable
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
- 有了Runnable,为啥还需要Callable呢,可以看到Runnable和Callable的两个不同,第一,Runnable是没有返回值的,第二,Runnable是不会抛出checked exception的,而有时候我们需要知道任务执行之后的返回,同时也希望利用异常机制完成一些逻辑。所以有了Callable。
- JUC中的Executors这个Factory类,提供了Runnable转Callable的方法。
Future
- future 是一个inteface,提供了一系列方法,来帮助我们获取异步执行的task的执行状况和执行结果。
FutureTask
- FutureTask实现了RunnableFuture接口,即既实现了Runnable接口,又实现了Future接口。所以他有两个功能,第一,作为一个task,提交到别的线程中异步执行,第二,通过future提供的一些接口,获取task的异步执行状态。
/**
* 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;
/** 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表示当前task的执行状态,其中,开始状态位NEW表示task还没开始执行。NORMAL,CANCELLED,INTERRUPTED为终态,COMPLETING和INTERRUPTING为临时状态,最终会通过上面的几个状态转移路径,转移到终态。
- callable,表示具体执行的任务。
- outcome, task 执行的返回结果
- runner,执行这个task的线程
- waiters,通过get方法获取此task执行结果被阻塞的线程。
- 看下几个核心的方法,我们知道,futuretask提交到别的线程里后,最终会调用task的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方法执行时,首先检查当前的状态是否是NEW,如果不是NEW说明已经被执行过了。开始执行之前,标记执行当前task的线程到runner。
- 调用callable的run方法,执行。抛异常时,设置setException。正常结束时,set结果。看下这两步里都会调到的finishCompletion方法。
/**
* 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
}
- 这里主要是在通知所有阻塞在watch这个task结果的线程,通知他们当前task已经执行结束了。
- 在执行结束时,看到finally里还有段逻辑
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);
}
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.
if (s == INTERRUPTING)
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();
}
- 这是在干嘛呢,是因为,即使我们在上一步通过set或者setException设置了当前task的状态,但可能有别的线程在通过调用cancel来设置当前task的状态,如果有的话,这里就自旋空转,直到cancel方法执行结束。
- 那cancel方法是怎么工作的呢
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;
}
- cancel方法其实就是通过找到执行当前task的runner,然后调用thread的interrupt方法,这里需要注意的是,thread.interrupt方法仅仅是设置一个标志位,具体线程有没有响应,要看自己的实现。反正这里就是调一把interrupt然后就走了,然后通知所有watch的线程。
- watch的线程,通过get方法获得执行结果是怎么拿到的呢
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);
}
}
- 核心逻辑就是,先把自己这个线程放到watch的waitNodes栈中,然后park 等待,直到task的状态>COMPLETING.
reference
FutureTask相关的更多相关文章
- java-concurrent包
通常所说的concurrent包基本有3个package组成 java.util.concurrent:提供大部分关于并发的接口和类,如BlockingQueue,Callable,Concurren ...
- java线程池和中断总结
目录 java线程池和中断总结 一. 线程池的使用 二. java中断机制 中断的处理 三. 线程间通信机制总结 java线程池和中断总结 本系列文是对自己学习多线程和平时使用过程中的知识梳理,不适合 ...
- Java并发之——线程池
一. 线程池介绍 1.1 简介 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡 ...
- Future 异步回调 大起底之 Java Future 与 Guava Future
目录 写在前面 1. Future模式异步回调大起底 1.1. 从泡茶的案例说起 1.2. 何为异步回调 1.2.1. 同步.异步.阻塞.非阻塞 1.2.2. 阻塞模式的泡茶案例图解 1.2.3. 回 ...
- 嵌入式单片机STM32应用技术(课本)
目录SAIU R20 1 6 第1页第1 章. 初识STM32..................................................................... ...
- maven工程打包出现Test相关的错误
----------------------------------------------------- T E S T S ------------------------------------ ...
- android相关技能
深读: 如:View.ViewGroup.AdapterView.ListView.GridView.Window.ViewDragHelper.ItemTouchHelper.SurfaceView ...
- Callable, Runnable, Future, FutureTask
Java并发编程之Callable, Runnable, Future, FutureTask Java中存在Callable, Runnable, Future, FutureTask这几个与线程相 ...
- 多线程并发执行任务,取结果归集。终极总结:Future、FutureTask、CompletionService、CompletableFuture
目录 1.Futrue 2.FutureTask 3.CompletionService 4.CompletableFuture 5.总结 ================正文分割线========= ...
随机推荐
- [Java] 部署到Linux
阿里云 控制台->云服务器ECS->实例->创建实例 计费方式 地域 网络 安全组:默认安全组 公网IP地址:分配 实例 公网带宽:1M ECS服务器:公共镜像CentOS 存储 购 ...
- 每天一个linux命令(49):at命令 atrm删除作业,由作业号标识。
atq命令 例如:从现在起三天后的下午四点运行作业at 4pm + 3 days:在July 31上午十点运行作业at 10am July 31:明天上午一点运行作业at 1am tomorrow. ...
- 查看linux系统是多少位,使用 getconf LONG_BIT
查看linux系统是多少位,使用 getconf LONG_BIT echo $HOSTTYPE
- Scala 函数式编程思想
Spark 选择 Scala 作为开发语言 在 Spark 诞生之初,就有人诟病为什么 AMP 实验室选了一个如此小众的语言 - Scala,很多人还将原因归结为学院派的高冷,但后来事实证明,选择 S ...
- Java 中布尔(boolean)类型占用多少个字节
为什么要问这个问题,首先在Java中定义的八种基本数据类型中,除了其它七种类型都有明确的内存占用字节数外,就 boolean 类型没有给出具体的占用字节数,因为对虚拟机来说根本就不存在 boolean ...
- MQTT简介-(转自cacard)
MQTT - MQ Telemetry Transport 轻量级的 machine-to-machine 通信协议. publish/subscribe模式. 基于TCP/IP. 支持QoS. ...
- iowait 的常见误解
转自:理解 %IOWAIT (%WIO):http://linuxperf.com/?p=33 %iowait 是 "sar -u" 等工具检查CPU使用率时显示的一个指标,在 ...
- Linux命令学习—— fdisk -l 查看硬盘及分区信息
Linux命令学习(3)-- fdisk -l 查看硬盘及分区信息注意:在使用fdisk命令时要加上sudo命令,否则什么也不能输出linux fdisk 命令和df区别是什么? fdisk工具是分区 ...
- 详解 WebRTC 高音质低延时的背后 — AGC(自动增益控制)
前面我们介绍了 WebRTC 音频 3A 中的声学回声消除(AEC:Acoustic Echo Cancellation)的基本原理与优化方向,这一章我们接着聊另外一个 "A" - ...
- 『言善信』Fiddler工具 — 1、Fiddler介绍与安装
目录 1.Fiddler简介 2.Fiddler功能 3.Fiddler工作原理 (1)先来了解一下B/S架构 (2)Fiddler工作原理 (3)Fiddler工作原理进阶说明 (4)以Google ...