Future接口和Callable接口以及FeatureTask详解
类继承关系

Callable接口
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
Callable接口中只有一个call()方法,和Runnable相比,该方法有返回值并允许抛出异常。
但是这里有一个问题,进程是要通过Thread类去创建的,但是Thread的target必须是实现了Runnable接口的类对象,所以Callable对象无法直接作为Thread对象的接口;所以要想作为target,必须同时实现Runnable接口。
Java提供了一个FutureTask类,该类实现了Runnable接口,该类的run()方法会调用Callable对象的call()方法,这样就能把Callable和Thread结合起来使用了。同时为了方便对Callable对象的操作,Java还提供了Future接口。
Future接口
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask类
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V> {
...
}
FutureTask是Runnable, Future接口的实现类。
下面看下FutureTask类的实现细节。
状态
/**
* 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;
FutureTask中定义了上述几种状态。
成员变量
/** 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;
构造函数
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
}
FutureTask(Callable callable)
这个构造方法比较简单,传入一个Callable对象。
FutureTask(Runnable runnable, V result)
先看一下Executors的callable方法:
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
这里只是创建RunnableAdapter对象,再看下RunnableAdapter类(是Executors的内部类):
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
这里的RunnableAdapter也是实现了Runnable接口,并通过call()方法调用最开始传入的Runnable对象的run()方法,并且返回最开始传入的result值。
这里实际上是将一个Runnable对象伪装成一个Callable对象,是适配器模式。
关键的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);
}
}
sun.misc.Unsafe是个什么东东?可以参考这里和这里。
UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread())
这行代码是什么含义呢?compareAndSwapObject可以通过反射,根据偏移量去修改对象,第一个参数表示要修改的对象,第二个表示偏移量,第三个参数用于和偏移量对应的值进行比较,第四个参数表示如果偏移量对应的值和第三个参数一样时要把偏移量设置成的值。翻译成人话就是:如果this对象的runnerOffset偏移地址的值为null,就把它设置为Thread.currentThread()。
那再来看看runnerOffset是啥:
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
对应的就是runner成员变量。
也就是说如果状态不是NEW或者runner不是null,run方法就直接返回。
try块中的方法就比较好理解了,就是调Callable对象的call()方法,并通过set方法设置result。
get方法
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
get方法主要是调用awaitDone方法阻塞等待结果,然后根据最终状态返回结果或抛出异常。
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根据当前状态直接返回或阻塞等待,代码流程不分析,主要看下几个关键的点。
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
WaitNode就是一个链表结构,用于记录等待当前FutureTask结果的线程。
注意,上面调用的LockSupport.park(this)和LockSupport.parkNanos(this, nanos)方法,LockSupport类是Java 6中引入的,提供了基本的线程同步原语,前面的两个调用会导致调用线程进入阻塞,直到run()方法中调用set(result)或者setException(ex)。
看看set()方法:
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
先设置state,并将结果赋给outcome,然后更新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
}
finishCompletion()的作用就是根据waiters链表,挨个唤醒等待FutureTask执行结果的线程,唤醒操作是通过LockSupport.unpark(t)实现的。
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;
}
cancle()就是根据是否可中断来设置state及中断状态。
参考文档
JDK源码
Future接口和Callable接口以及FeatureTask详解的更多相关文章
- Java生鲜电商平台-APP/小程序接口传输常见的加密算法及详解
Java生鲜电商平台-APP/小程序接口传输常见的加密算法及详解 说明:Java生鲜电商平台-APP/小程序接口传输常见的加密算法及详解,加密算法,是现在每个软件项目里必须用到的内容. 广泛应用在包括 ...
- C#二次开发BIMFACE系列61 File Management文件管理服务接口二次开发及实战详解
系列目录 [已更新最新开发文章,点击查看详细] 在我的博客<C#二次开发BIMFACE系列61 File Management文件管理服务接口二次开发及实战详解>最后列出了 Fil ...
- 前台主页搭建、后台主页轮播图接口设计、跨域问题详解、前后端互通、后端自定义配置、git软件的初步介绍
今日内容概要 前台主页 后台主页轮播图接口 跨域问题详解 前后端打通 后端自定义配置 git介绍和安装 内容详细 1.前台主页 Homeviwe.vue <template> <di ...
- Go语言接口内部布局和方法集详解
1. 接口值内部布局 如果用户定义的类型实现了某个接口类型声明的一组方法,那么这个用户定义的类型的值就可以赋给这个接口类型的值.这个赋值会把用户定义的类型的值存入接口类型的值.赋值完成后得到的值称 ...
- 【多线程学习(2)】继承Thread类和实现Runnable接口、Callable接口的区别
1)Runnable和Callable同是接口 * Callable的任务执行后可返回值,而Runnable的任务是不能返回值(是void);call方法可以抛出异常,run方法不可以 * 运行Cal ...
- 接口调试之Postman 使用方法详解
一.Postman背景介绍 用户在开发或者调试网络程序或者是网页B/S模式的程序的时候是需要一些方法来跟踪网页请求的,用户可以使用一些网络的监视工具比如著名的Firebug等网页调试工具.今天给大家介 ...
- Spring Boot 2.x基础教程:Swagger接口分类与各元素排序问题详解
之前通过Spring Boot 2.x基础教程:使用Swagger2构建强大的API文档一文,我们学习了如何使用Swagger为Spring Boot项目自动生成API文档,有不少用户留言问了关于文档 ...
- Runnable接口和Callable接口的区别
Runnable接口中的run()方法的返回值是void,它做的事情只是纯粹地去执行run()方法中的代码而已:Callable接口中的call()方法是有返回值的,是一个泛型,和Future.Fut ...
- YAPI接口自动鉴权功能部署详解
安装准备 以下操作,默认要求自己部署过yapi,最好是部署过yapi二次开发环境. 无论是选择在线安装或者是本地安装,都需要安装client工具. 1.yapi-cli:npm install yap ...
随机推荐
- Go语言高级特性总结——Struct、Map与JSON之间的转化
Struct与Map之间互相转换 // Struct2Map convert struct to map func Struct2Map(st interface{}) map[string]inte ...
- 用cglib包来为类产生动态代理类对象
一:在JDK里也有动态代理的类和接口,是Proxy和InvocationHandler,但是Proxy只能为接口产生代理类,借助InvocationHandler的实现类来完成对类对象的代理: 但是在 ...
- MySQL RR模式下如何加锁
锁的算法有三种,如下: record lock.gap lock.next_key lock 在不同的隔离级别下,所使用的锁的算法如下: RC:仅有record 锁 RR:有record和next_k ...
- 利用WCF搭建RESTful--纯代码启动
最近学习了这几年忽略了的当前几乎所有的开发技术,有深有浅,而服务层最有兴趣的是RESTfull,看的是java的书.因为不熟悉JSP,于是找了本书细细研读了一次. dotnet的实现也相对简单,网上也 ...
- hud 3123 GCC
题目 输入:n 和 mod 输出: Output the answer of (0! + 1! + 2! + 3! + 4! + ... + n!)%m. Constrains 0 < T &l ...
- URL中文编码
/// <summary> /// GB2312编码 /// </summary> /// <param name=" ...
- hdu4048
题意:给定m个数,还有n,n表示有一个长度为n的环,现在要求从M个数中选出若干个数,要求选出的数最大公约数为1,填充在n个位置中,选出的数可以重复,求多少种种方案.旋转当成一样的 . 思路:假设现在选 ...
- Java学习--数组与方法
1. public class MethodDemo01{ public static void main(String args[]){ printInfo() ; // 调用printInfo() ...
- poj 2676 如何填满九宫格
Sudoku Time Limit: 2000 MS Memory Limit: 65536 KB 64-bit integer IO format: %I64d , %I64u Java class ...
- 5.css背景以及书写位置
1.样式表书写位置 ◆内嵌式写法 <head> <style type=”text/css”> 样式表写法 </style> </head> 2.◆外链 ...