JDK源码那些事儿之FutureTask

上一篇文章中我们已经介绍了ThreadPoolExecutor线程池,在通过submit方法提交执行任务时曾提及可以跟踪任务执行状态的FutureTask,那么在jdk中是如何实现的呢?

前言

JDK版本号:1.8.0_171

在使用ThreadPoolExecutor时如果我们不需要获取任务执行的状态和结果,直接调用ThreadPoolExecutor.execute(Runnable command)方法即可,然而当我们需要知道提交的任务执行状态和结果时,我们该如何进行呢?

jdk本身为我们提供了Callable接口和Future接口来实现我们需要的功能。其中FutureTask是实现了Future接口的实现类

FutureTask可用于异步获取执行结果或取消执行任务。通过传入Runnable或者Callable的任务给FutureTask(可以在下面的构造方法源码中看到),直接调用其run方法或者放入线程池执行,之后可以在外部通过FutureTask的get方法异步获取执行结果。所以,FutureTask适用于比较耗时的计算,主线程可以在完成自己的任务后,再去获取结果以减少等待的消耗

Callable

类似于Runnable,和Runnable不同的是run方法无任何返回值,而Callable提供了call泛型接口,返回类型是传递进来的V类型,同时也可以进行抛错处理,返回值也就是我们提交任务之后执行完毕获得的结果,我们可以获得任务执行结果进行后续的其他处理

@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;
}

Future

Future是一个接口,定义了实现Runnable或者Callable接口的任务基本操作方法,主要分为3类:

  • 取消任务执行
  • 获取任务执行状态
  • 获取任务执行结果

其中获取执行结果也就需要用到我们上面提到的Callable接口

public interface Future<V> {
    
    // 取消任务,mayInterruptIfRunning为是否允许取消正在执行却没有执行完毕的任务
    boolean cancel(boolean mayInterruptIfRunning);
    // 任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true
    boolean isCancelled();
    // 任务是否已经完成,若任务完成,则返回true
    boolean isDone();
    // 获取执行结果,这个方法会阻塞,一直等到任务执行完毕才返回
    V get() throws InterruptedException, ExecutionException;
    // 获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

类定义

我们可以看到FutureTask最终同时实现了Runnable,Future接口,故它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值

public class FutureTask<V> implements RunnableFuture<V>

关系图

常量/变量

    // 任务运行状态
    private volatile int state;
    // 7种状态
    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 */
    // 构造时传入实现Callable接口的任务
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    // 保存执行结果或异常信息,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;
    
    // Unsafe mechanics
    // CAS相关
    private static final sun.misc.Unsafe UNSAFE;
    private static final long stateOffset;
    private static final long runnerOffset;
    private static final long waitersOffset;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = FutureTask.class;
            stateOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("state"));
            runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));
            waitersOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("waiters"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

其中任务运行状态的转换注释部分也进行了说明,可能的状态转换如下:

  • NEW -> COMPLETING -> NORMAL
  • NEW -> COMPLETING -> EXCEPTIONAL
  • NEW -> CANCELLED
  • NEW -> INTERRUPTING -> INTERRUPTED

7种状态进行以下说明方便各位参照上面状态转换进行理解:

  • NEW:表示是新创建任务或者还没被执行完的任务
  • COMPLETING:任务已经执行完成或者执行任务的时候发生异常,但是任务执行结果或者异常原因还没有保存到outcome,属于中间状态
  • NORMAL:任务已经执行完成并且任务执行结果已经保存到outcome,状态会从COMPLETING转换到NORMAL,属于最终状态
  • EXCEPTIONAL:任务执行发生异常并且异常原因已经保存到outcome,状态会从COMPLETING转换到EXCEPTIONAL,属于最终状态
  • CANCELLED:任务还没开始执行或者已经开始执行但是还没有执行完成的时候,用户调用了cancel(false)方法取消任务且不中断任务执行线程,这个时候状态会从NEW转化为CANCELLED状态,同样属于最终状态
  • INTERRUPTING:任务还没开始执行或者已经执行但是还没有执行完成的时候,用户调用了cancel(true)方法取消任务并且要中断任务执行线程但是还没有中断任务执行线程之前,状态会从NEW转化为INTERRUPTING,属于中间状态
  • INTERRUPTED:调用interrupt()中断任务执行线程之后状态会从INTERRUPTING转换到INTERRUPTED,属于最终状态

可参考下图理解:


状态转换图

构造方法

构造方法有两个,针对Callable接口和Runnable接口的任务,任务状态初始设置为NEW

    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) {
        // Runnable封装成Callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

回想之前ThreadPoolExecutor中的submit,查看抽象类AbstractExecutorServicesubmit方法,可以看到重载了多个方法,通过newTaskFor先进行一层包装,而newTaskFor中就是使用了FutureTask的两种构造方法完成包装,然后再继续执行execute方法

    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

重要方法

get

获取任务执行结果,参考状态转换图,在COMPLETING之前的状态还未将结果保存,故需要通过awaitDone阻塞等待,等待任务结果被保存或者超时抛错,然后调用report获取任务结果

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

    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

awaitDone

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()) {
                // 移除等待队列中的WaitNode
                removeWaiter(q);
                // 抛错
                throw new InterruptedException();
            }
            
            // 执行完成,异常或取消
            // 返回状态值
            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            // 处于COMPLETING状态
            // 任务执行完毕还未保存执行结果到outcome
            // 让步操作
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            // 等待节点为空,则新创建
            else if (q == null)
                q = new WaitNode();
            // 还未入队则更新waiters
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            // 设置了等待超时
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    // 已经超时则移除等待队列的节点q
                    removeWaiter(q);
                    // 返回任务状态
                    return state;
                }
                // 还未超时则继续阻塞等待
                LockSupport.parkNanos(this, nanos);
            }
            // 阻塞等待
            else
                LockSupport.park(this);
        }
    }

report

被get方法调用,返回任务执行结果(也就是outcome)或者抛出错误

    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);
    }

isCancelled

判断任务是否被取消,包含CANCELLED,INTERRUPTING,INTERRUPTED状态,参考上面状态转换图可以看出,在调用cancel方法后任务状态转换会返回true

    public boolean isCancelled() {
        return state >= CANCELLED;
    }

isDone

判断任务是否执行完毕,非NEW状态,其他状态都属于任务执行完毕,不管是异常还是取消或者正常执行完成,参考上面状态转换图的说明

    public boolean isDone() {
        return state != NEW;
    }

cancel

取消任务执行,mayInterruptIfRunning参数为是否允许取消正在执行却没有执行完毕的任务

    public boolean cancel(boolean mayInterruptIfRunning) {
        // 非新创建/任务执行中或处于NEW状态并且更新状态失败则直接返回false,更新成功才继续下面代码执行
        // 参考任务状态转换图
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                // true的时候获取线程执行interrupt
                // 也就是中断已经执行的任务线程
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    // CAS更新state
                    // 对应状态转换图中的最后一个
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            // 后续处理
            finishCompletion();
        }
        return true;
    }

run

最终任务线程执行的方法,就和Thread的run方法一样,主要流程如下:

  • 判断当前任务状态,若已执行完毕或取消了则直接返回,状态为NEW时判断CAS更新runner失败也直接返回
  • 执行任务
  • 获取任务执行结果
  • 设置任务状态同时设置执行结果
    public void run() {
        // 任务已经执行完毕或者取消了则直接返回
        // 任务为NEW状态,则尝试将当前执行线程保存到runner,成功则继续执行,失败则直接返回
        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) {
                    // 执行异常设置执行结果为null
                    // 并通过setException完成状态转换和后续处理
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    // 正常执行完毕则通过set完成状态转换和后续处理
                    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);
        }
    }

set

设置任务正常执行完成后的结果,在run方法中被调用,我们可以看到方法中CAS两次更新任务执行状态,对应状态转换图中第一种情况 NEW -> COMPLETING -> NORMAL

    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            // outcome保存任务结果
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            // 后续处理
            finishCompletion();
        }
    }

setException

与set类似,主要是在任务执行出现异常时调用,同样对应于状态转换图中第二种情况 NEW -> COMPLETING -> EXCEPTIONAL

    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

finishCompletion

任务正常执行,异常或者取消都会执行,遍历waiters链表,唤醒所有节点中的等待线程,然后把其中的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;
                        // 释放,awaitDone有对应的LockSupport.park
                        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
    }

runAndReset

与run类似,不同之处在于不会保存任务执行结果同时如果正常执行完毕不会调用set方法更新任务状态,与Runnable任务类似

    protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    // 抛错会调用setException
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

removeWaiter

移除等待链表waiters中的node节点

    private void removeWaiter(WaitNode node) {
        // 非空校验
        if (node != null) {
            node.thread = null;
            // 更新waiters
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
                    else if (pred != null) {
                        pred.next = s;
                        if (pred.thread == null) // check for race
                            continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

总结

至此,关于FutureTask的源码基本已分析完毕,本质上而言不是过于复杂,实现Callable()接口的任务,然后把任务提交给线程池,由线程池完成执行,我们只需要通过get方法获取执行结果即可,同时也可以取消任务的执行,方便操作。其中FutureTask本身还拥有7种状态,可以参考状态转换图理解,也可以更好的理解其源码实现

以上内容如有问题欢迎指出,笔者验证后将及时修正,谢谢

猜你喜欢

转载自www.cnblogs.com/freeorange/p/12375811.html