Executor框架使用Runnable做为其基本的任务表示形式。Runnable是一种有很大局限的抽象,它不能返回一个值或抛出一个受检查的异常。Runnable接口:html
public interface Runnable { public abstract void run(); }
许多任务实际上都是存在延迟的计算,对于这些任务,Callable是一种更好的抽象:它会返回一个值,并可能抛出一个异常。Callable接口:git
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描述的都是抽象的计算任务。这些任务一般是有生命周期的。Executor执行的任务有4个生命周期阶段:建立、提交、开始和完成。因为有些任务可能要执行很长时间,所以一般但愿能够取消这些任务。在Executor框架中,已提交但还没有开始的任务能够取消,对于已经开始执行的任务,只有当它们响应中断时才能取消。github
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表示是否容许取消正在执行却没有执行完毕的任务,若是设置true,则表示能够取消正在执行过程当中的任务。若是任务已经完成,则不管mayInterruptIfRunning为true仍是false,此方法确定返回false,即若是取消已经完成的任务会返回false;若是任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;若是任务尚未执行,则不管mayInterruptIfRunning为true仍是false,确定返回true。数据结构
isCancelled方法表示任务是否被取消成功,若是在任务正常完成前被取消成功,则返回 true。并发
isDone方法表示任务是否已经完成,若任务完成,则返回true;框架
get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;异步
get(long timeout, TimeUnit unit)用来获取执行结果,若是在指定时间内,还没获取到结果,就直接返回null。函数
也就是说实际上Future提供了三种功能:ui
Future与Callable的关系与ExecutorService与Executor的关系对应。
Future只是一个接口,没法直接建立对象,所以有了FutureTask。
咱们先来看下FutureTask的实现:
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }
FutureTask的继承关系和方法如图所示:
FutureTask是一个可取消的异步计算,FutureTask 实现了Future的基本方法,提供start cancel 操做,能够查询计算是否已经完成,而且能够获取计算的结果。结果只能够在计算完成以后获取,get方法会阻塞当计算没有完成的时候,一旦计算已经完成, 那么计算就不能再次启动或是取消。
一个FutureTask 能够用来包装一个 Callable 或是一个Runnable对象。由于FurtureTask实现了Runnable方法,因此一个 FutureTask能够提交(submit)给一个Excutor执行(excution). 它同时实现了Callable, 因此也能够做为Future获得Callable的返回值。
FutureTask有两个很重要的属性分别是state和runner, FutureTask之因此支持canacel操做,也是由于这两个属性。
其中state为枚举值:
private volatile int state; // 注意volatile关键字 /** * 在构建FutureTask时设置,同时也表示内部成员callable已成功赋值, * 一直到worker thread完成FutureTask中的run(); */ private static final int NEW = 0; /** * woker thread在处理task时设定的中间状态,处于该状态时, * 说明worker thread正准备设置result. */ private static final int COMPLETING = 1; /** * 当设置result结果完成后,FutureTask处于该状态,表明过程结果, * 该状态为最终状态final state,(正确完成的最终状态) */ private static final int NORMAL = 2; /** * 同上,只不过task执行过程出现异常,此时结果设值为exception, * 也是final state */ private static final int EXCEPTIONAL = 3; /** * final state, 代表task被cancel(task尚未执行就被cancel的状态). */ private static final int CANCELLED = 4; /** * 中间状态,task运行过程当中被interrupt时,设置的中间状态 */ private static final int INTERRUPTING = 5; /** * final state, 中断完毕的最终状态,几种状况,下面具体分析 */ private static final int INTERRUPTED = 6;
state有四种可能的状态转换:
其余成员变量:
/** The underlying callable; nulled out after running */ private Callable<V> callable; // 具体run运行时会调用其方法call(),并得到结果,结果时置为null. /** The result to return or exception to throw from get() */ private Object outcome; // non-volatile, protected by state reads/writes 不必为votaile,由于其是伴随state 进行读写,而state是FutureTask的主导因素。 /** The thread running the callable; CASed during run() */ private volatile Thread runner; //具体的worker thread. /** Treiber stack of waiting threads */ private volatile WaitNode waiters; //Treiber stack 并发stack数据结构,用于存放阻塞在该futuretask#get方法的线程。
下面分析下Task的状态变化,也就一个任务的生命周期:
建立一个FutureTask首先调用构造方法:
public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); this.state = NEW; // ensure visibility of callable }
this.callable = Executors.callable(runnable, 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); }
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; } }
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, 判断runner是否为null, 若是为null, 则把当前执行任务的线程赋值给runner,若是runner不为null, 说明已经有线程在执行,返回。此处使用cas来赋值worker thread是保证多个线程同时提交同一个FutureTask时,确保该FutureTask的run只被调用一次, 若是想运行屡次,使用runAndReset()方法。
这里
!UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())
if (this.runner == null ){ this.runner = Thread.currentThread(); }
接着开始执行任务,若是要执行的任务不为空,而且state为New就执行,能够看到这里调用了Callable的call方法。若是执行成功则set结果,若是出现异常则setException。最后把runner设为null。
接着看下set方法:
protected void set(V v) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = v; UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state finishCompletion(); } }
最后执行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很是重要的get方法:
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); }
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); }
若是get时,FutureTask的状态为未完成状态,则调用awaitDone方法进行阻塞。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); } }
若是执行get的线程被中断,则移除FutureTask的全部阻塞队列中的线程(waiters),并抛出中断异常;
若是FutureTask的状态转换为完成状态(正常完成或取消),则返回完成状态;
若是FutureTask的状态变为COMPLETING, 则说明正在set结果,此时让线程等一等;
若是FutureTask的状态为初始态NEW,则将当前线程加入到FutureTask的阻塞线程中去;
若是get方法没有设置超时时间,则阻塞当前调用get线程;若是设置了超时时间,则判断是否达到超时时间,若是到达,则移除FutureTask的全部阻塞列队中的线程,并返回此时FutureTask的状态,若是未到达时间,则在剩下的时间内继续阻塞当前线程。
注:本文源码基于JDK1.7。(1.6经过AQS实现)