一、Callable、Future和FutureTask概述
1、Callable和Runnable的区别
Executor框架使用Runnable作为其基本的任务表示形式。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();
}
许多任务实际上都是存在延迟的计算,对于这些任务,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;
}
2、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;
}
cancel方法用于取消任务,取消成功返回true,取消失败返回false。mayInterruptIfRunning参数含义是是否允许取消正在运行的任务。
isCancelled方法用于判断任务是否被取消成功,在任务正常结束之前被取消成功则会返回true。
isDone方法用于判断任务是否已经完成
get用于获取任务的返回值
get(long timeout, TimeUnit unit) 用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
综上所述Future提供了三种功能
1、判断任务是否完成
2、中断任务
3、获取结果
3、FutureTask
Future只是一个接口,无法直接创建对象,因此需要借助FutureTask来使用
public class FutureTask<V> implements RunnableFuture<V> {}
FutureTask实现了RunnableFuture接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
RunnableFuture继承自Runnable和Future
一个FutureTask 可以用来包装一个 Callable 或是一个Runnable对象。因为FurtureTask实现了Runnable方法,所以一个 FutureTask可以提交(submit)给一个Excutor执行(excution). 它同时实现了Callable, 所以也可以作为Future得到Callable的返回值。
FutureTask有两个很重要的属性分别是state和runner
/**
* 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 -> COMPLETING -> NORMAL(正常结束)
- NEW -> COMPLETING -> EXCEPTIONAL(异常结束)
- NEW -> CANCELLED(取消执行)
- NEW-INTERRUPTING-INTERRUPTED(被中断)
通过几种成员方法讲述下状态的转换
1、构造函数
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Callable}.
*
* @param callable the callable task
* @throws NullPointerException if the callable is null
*/
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
* {@code Future<?> f = new FutureTask<Void>(runnable, null)}
* @throws NullPointerException if the runnable is null
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
可以看到任务被创建时的初始状态是NEW,构造函数有2种重载函数,一种接收Runnable,一种接收Callable,接收Runnable的时候会进行将Runnable转为Callable。如下
/**
* Returns a {@link Callable} object that, when
* called, runs the given task and returns the given result. This
* can be useful when applying methods requiring a
* {@code Callable} to an otherwise resultless action.
* @param task the task to run
* @param result the result to return
* @param <T> the type of the result
* @return a callable object
* @throws NullPointerException if task null
*/
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
/**
* A callable that runs given task and returns given result
*/
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;
}
}
可以看到就是让传入的参数作为call的返回值。使用call方法来调用run方法即可。把传入的 T result 作为callable的返回结果
启动任务
当创建完一个Task通常会提交给Executors来执行,当然也可以使用Thread来执行,Thread的start()方法会调用Task的run()方法。看下FutureTask的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);
}
}
首先判断任务是否处于NEW的状态,如果不是则直接返回。因为任务在初始化完成之前可能就直接被cancel,这时任务已经不处于NEW状态,可能处于Interrupting状态,这也是任务没完全启动,取消时任务一直得不到启动的原因。
如果是处于NEW状态,则判断task的线程是否为null,如果不为null,说明已经有线程在运行了,直接返回。如果为null,则将当前线程赋值给task的线程。此处使用CAS是为了保证对work Thread的赋值是原子性操作。保证多个线程对task进行提交的时候,run只被调用一次。
接下来任务不为null,并且任务处于NEW状态就启动。正常执行就set结果,否则就setException。最后把work Thread设置为null。
set方法
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon successful completion of the computation.
*
* @param v the value
*/
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
可以看到,如果task处于NEW,则付值为COMPLETING,再将结果设置到outcome中,再将任务设置成NORMAL状态。
整个状态的流转就是上面提到的:- NEW -> COMPLETING -> NORMAL(正常结束)
最后调用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
}
```java
可以看到主要任务是唤醒等待在task上的所有线程,WaitNode存放的是所有调用get方法阻塞在该task上的线程。
调用done方法;将task的任务设置成null。至此结束整个run的流程。
接下来看下get方法
```java
/**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
可以看到,第一步是判断任务的状态是否是完成状态,如果是完成状态,则调用report方法
/**
* Returns result or throws exception for completed task.
*
* @param s completed state value
*/
@SuppressWarnings("unchecked")
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);
}
如果任务状态NORMAL,则表示任务正常结束,已经设置了返回值,直接返回。如果任务是取消或者中断则表示任务异常,则抛出异常。
如果get时,FutureTask的状态为未完成状态,则调用awaitDone方法进行阻塞。awaitDone():
/**
* 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可以看作是轮询查询status的变化,在get阻塞的期间
1、如果调用get的线程被中断,则移除所有阻塞在等待队列上的线程,并抛出InterruptedException异常。
2、如果status表示任务已经完成(正常完成、被取消)直接返回任务状态
3、如果任务正在执行,证明此时正在set结果,让线程等待下。
4、如果线程是NEW状态,将该线程加入到等待队列当中
5、如果get未设置超时时间,则让线程继续阻塞
6、设置了超时时间检查时间是否已到,到了的话移除所有的等待线程,并返回当前的任务status,没到的话继续等待。
四、举例说明Callable、Future和FutureTask框架的使用
package cn.enjoy.controller.thread;
import cn.enjoy.controller.thread.DBPOLL.SleepTools;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* @author:wangle
* @description:
* @version:V1.0
* @date:2020-03-23 21:55
**/
public class CallableFutureFutureTask {
private static class UseCallable implements Callable<Integer> {
@Override
public Integer call()throws Exception{
Integer i =0;
System.out.println("Callable开始计算");
for( i=0;i<100000;i++){
System.out.println("run");
System.out.println(Thread.currentThread().isInterrupted());
if(Thread.currentThread().isInterrupted()){
System.out.println("线程被中断");
break;
}
}
System.out.println("线程done");
return i;
}
}
public static void main(String[] args)throws Exception{
UseCallable useCallable = new UseCallable();
FutureTask<Integer> futureTask = new FutureTask<Integer>(useCallable);
Thread testThread = new Thread(futureTask);
testThread.start();
Thread.sleep(1000);
futureTask.cancel(true);
System.out.println(futureTask.get());
SleepTools.second(2);
}
}
1、cancel后,任务直接被终止结束,因为我在线程中进行捕获了中断进行了处理,如果不进行处理则不会被中断,感兴趣的可以试试。(因为java的线程是协作的,并非是抢占的)
2、调用get方法后会一直阻塞到任务执行完成。
注
本文源码来自JDK1.8,1.6是使用AQS实现