FutureTask实现异步的分析

1.FutureTask的类结构

首先咱们看下FutureTask的类型的继承关系,它同时实现了Future和Runnable的接口,也就是 具有了Future的异步的功能. promise

2. Future的定义

public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
复制代码

能够看到Future是JDK1.5引入的异步的方式,而FutureTask则是异步的实现,它 提供了取消任务、检测是取消、是否完成、获取执行结构等操做, 其中获取结果若是 任务没有执行完成,会阻塞任务的执行.直到任务返回结果.markdown

3. 任务状态转换

全部可能的状态转换:
NEW(新建立) -> COMPLETING(完成中) -> NORMAL(正常结束)
NEW(新建立) -> COMPLETING(完成中) -> EXCEPTIONAL(异常结束)
NEW(新建立) -> CANCELLED(取消)
NEW(新建立) -> INTERRUPTING(中断中) -> INTERRUPTED(中断完成) \异步

4 FutureTask任务执行

public void run() {
       if (state != NEW ||
           !RUNNER.compareAndSet(this, 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);
       }
   }
复制代码

其实现异步的关键,在于最后任务执行完成, 将任务执行的执行的结果从新甚至回FutureTask的outcome字段,而后经过get方法能够获取异步任务返回的结果,this

5 FutureTask的get方法获取异步任务结构

public V get() throws InterruptedException, ExecutionException {
      int s = state;
      if (s <= COMPLETING)
          s = awaitDone(false, 0L);
      return report(s);
  }
复制代码

能够看出,在调用get方法时, 若是任务state是小于COMPLETING,说明任务还在进行中, 则调用awaitDone进行阻塞等待任务执行,spa

private int awaitDone(boolean timed, long nanos)
       throws InterruptedException {
       // The code below is very delicate, to achieve these goals:
       // - call nanoTime exactly once for each call to park
       // - if nanos <= 0L, return promptly without allocation or nanoTime
       // - if nanos == Long.MIN_VALUE, don't underflow
       // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
       //   and we suffer a spurious wakeup, we will do no worse than
       //   to park-spin for a while
       long startTime = 0L;    // Special value 0L means not yet parked
       WaitNode q = null;
       boolean queued = false;
       for (;;) {
           int s = state;
           if (s > COMPLETING) {
               if (q != null)
                   q.thread = null;
               return s;
           }
           else if (s == COMPLETING)
               // We may have already promised (via isDone) that we are done
               // so never return empty-handed or throw InterruptedException
               Thread.yield();
           else if (Thread.interrupted()) {
               removeWaiter(q);
               throw new InterruptedException();
           }
           else if (q == null) {
               if (timed && nanos <= 0L)
                   return s;
               q = new WaitNode();
           }
           else if (!queued)
               queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
           else if (timed) {
               final long parkNanos;
               if (startTime == 0L) { // first time
                   startTime = System.nanoTime();
                   if (startTime == 0L)
                       startTime = 1L;
                   parkNanos = nanos;
               } else {
                   long elapsed = System.nanoTime() - startTime;
                   if (elapsed >= nanos) {
                       removeWaiter(q);
                       return state;
                   }
                   parkNanos = nanos - elapsed;
               }
               // nanoTime may be slow; recheck before parking
               if (state < COMPLETING)
                   LockSupport.parkNanos(this, parkNanos);
           }
           else
               LockSupport.park(this);
       }
   }
复制代码

能够看出这里是经过是LockSupport.park进行现成阻塞,直到任务完成,线程

总结:
今天主要是分析JDK的Future实现类的FutureTask实现异步的方式,若是是向线程池提交任务,任务是有线程池的工做线程执行,而不会阻塞住线程, 可是JDK并非真正意义上的异步,由于提交任务后,当即执行get获取结果,依然是回同步阻塞的,而Netty的Promise 则是异步的回调的方式实现异步,是JDK的异步的加强,有兴趣的同窗能够看下它的实现,之后有机会会再次分享出来.code