Fututre初解

本文详细解读了Java中的Future接口及其实现FutureTask,介绍了如何进行异步计算、取消任务、设置超时获取结果以及处理可能出现的异常情况。FutureTask是可取消的异步计算工具,支持包装Callable和Runnable对象,执行完成后可通过get方法获取结果。
摘要由CSDN通过智能技术生成

Fututre初解

前言

Future 接口 表示异步计算的结果。提供了检查计算是否完成、等待计算完成以及检索计算结果的方法。只有在计算完成后才能使用方法 get 检索结果,必要时会阻塞,直到准备就绪。

源码解析

接口

 public interface Future<V> {

    /**
     * 尝试取消此任务的执行。如果任务已完成、已取消或由于其他原因无法取消,则此尝试将失败。
     * 如果成功,并且调用cancel时此任务尚未启动,则此任务不应运行。
     * 如果任务已启动,则该 mayInterruptIfRunning 参数确定是否应中断执行此任务的线程以尝试停止任务。
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * 如果此任务在正常完成之前被取消,则返回 true 
     */
    boolean isCancelled();

    /**
     * 如果此任务已完成,则返回 true 。
     * 完成可能是由于正常终止、异常或取消 -- 在所有这些情况下,此方法将返回 true。
     */
    boolean isDone();

    /**
     * 如有必要,等待计算完成,然后检索其结果。
     * 返回:计算结果
     * 抛出:
     * CancellationException – 如果计算被取消
     * ExecutionException – 如果计算抛出异常
     * InterruptedException – 如果当前线程在等待时被中断
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * 如有必要,最多等待给定时间以完成计算,然后检索其结果(如果可用)。
     *   参数:
     *   timeout – 等待的最长时间 unit – 超时参数的时间单位
     *   返回:计算结果
     *   抛出:
     *   CancellationException – 如果计算被取消
     *   ExecutionException – 如果计算抛出异常
     *   InterruptedException – 如果当前线程在等待时被中断
     *   TimeoutException – 如果等待超时
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}                        

总结

  • 包含获取异步结果、取消任务、超时获取异步结果等方法

FutureTask(实现Future接口的类之一)解析

前言

可取消的异步计算。此类提供 的基本实现 Future,其中包含启动和取消计算、查询以查看计算是否完成以及检索计算结果的方法。只有在计算完成后才能检索结果;如果计算尚未完成,这些 get 方法将阻塞。计算完成后,无法重新启动或取消计算(除非使用 runAndReset调用计算)。
A FutureTask 可用于包装 Callable or Runnable 对象。因为 FutureTask implements Runnable, FutureTask a 可以提交到 an Executor 执行。
除了作为独立类之外,此类还提供 protected 在创建自定义任务类时可能有用的功能

public class FutureTask<V> implements RunnableFuture<V> {}

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

总结

  • FutureTask实现了RunnableFuture接口
  • RunnableFuture继承自Runnable和Future所以FutureTask可以提交到Executor执行

构造方法

包含两个构造方法,分别接收Callable和Runnable实例

    //与Runnable相比,Callable是一个具有返回值的任务
	public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        //记录当前任务
        this.callable = callable;
        //设置当前状态为NEW
        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) {
        //将Runnable包装成Callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of 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> { //适配器 将一个runnable 包装成一个callable
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }

	//一个Callable记录当前任务
	private Callable<V> callable;

在FutureTask类中有几个标识当前任务执行的状态

    private volatile int state; //当前任务的状态字段
    private static final int NEW          = 0; //表示一个新的任务,初始状态
    private static final int COMPLETING   = 1; //当任务被设置结果时,处于COMPLETING状态,这是一个中间状态。
    private static final int NORMAL       = 2; //表示任务正常结束。
    private static final int EXCEPTIONAL  = 3; //表示任务因异常而结束
    private static final int CANCELLED    = 4; //任务还未执行之前就调用了cancel(true)方法,任务处于取消状态
    private static final int INTERRUPTING = 5; //当任务调用cancel(true)中断程序时,任务处于INTERRUPTING状态,这是一个中间状态。
    private static final int INTERRUPTED  = 6; //任务调用cancel(true)中断程序时会调用interrupt()方法中断线程运行,任务状态由INTERRUPTING转变为INTERRUPTED
	//状态转换的几种形式 在任务执行完成之后才会改变NEW状态(所有达到最终状态,都会调用finishCompletion()方法,唤醒等待获取结果的线程)
	//NEW->COMPLETING->NORMAL(正常结束)
	//NEW->COMPLETING->EXCEPTIONAL(任务出现异常结束)
	//NEW->CANCELLED(任务被取消)
	//NEW->INTERRUPTING->INTERRUPTED(任务被中断)
		

run方法(Runnable方法)

	private volatile Thread runner; //执行任务的线程   
	private Object outcome; //要返回的结果或要从 get() 抛出的异常

	//任务执行调用此方法 只有一个线程会执行此任务
	public void run() {
        //如果状态不是初始状态 或者设置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) {
                    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()
            // 设置当前执行线程为null
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            //正在中断或已经中断状态 在任务执行前被取消了(中断)
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
	//设置任务执行结果
    protected void set(V v) {
        //设置状态为已完成
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            //设置状态为正常结束
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            //任务执行完成
            finishCompletion();
        }
    }

    /**
         * Causes this future to report an {@link ExecutionException}
         * with the given throwable as its cause, unless this future has
         * already been set or has been cancelled.
         *
         * <p>This method is invoked internally by the {@link #run} method
         * upon failure of the computation.
         *
         * @param t the cause of failure
         */
	//设置任务执行出现的异常
    protected void setException(Throwable t) {
        //设置当前futureTask状态为已完成
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //设置outcome为异常信息
            outcome = t;
            //设置状态为因为异常而结束的状态
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            //任务执行完成
            finishCompletion();
        }
    }

finishCompletion()方法

删除所有等待的线程并发出信号,调用 done(),并取消可调用线程。在任务完成后即可通知获取结果的线程去获取结果,在任务执行过程中获取结果的线程会被阻塞。

    private volatile WaitNode waiters;//等待结果线程的队列
	//是一个单向链表
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            //任务执行完成 将等待获取结果的线程 设为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
    }

cancel(boolean mayInterruptIfRunning)方法

取消当前任务方法,如果任务未启动则直接设为CANCELLED,如果任务正在运行根据参数判断是否需要中断运行线程

    //任务在执行过程中只要没有完成就是NEW状态
	public boolean cancel(boolean mayInterruptIfRunning) {
        //1.任务已经不处于NEW状态则取消失败
        //2.任务处于NEW状态,但是更新状态为INTERRUPTING或者CANCELLED失败了则也取消失败
        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);//以可见方式设置FutureTask状态
                }
            }
        } finally {
            //调用任务已经完成方法
            finishCompletion();
        }
        return true;
    }

	//当任务在执行过程中进行了中断取消则在任务执行完成后调用此方法
	//当任务在执行之前调用的中断取消则不会执行任务但会执行此方法
    private void handlePossibleCancellationInterrupt(int s) {
        // It is possible for our interrupter to stall before getting a
        // chance to interrupt us.  Let's spin-wait patiently.
        if (s == INTERRUPTING)
            //放弃当前CPU知道变为INTERRUPTED
            while (state == INTERRUPTING)
                Thread.yield(); // wait out pending interrupt

        // assert state == INTERRUPTED;

        // We want to clear any interrupt we may have received from
        // cancel(true).  However, it is permissible to use interrupts
        // as an independent mechanism for a task to communicate with
        // its caller, and there is no way to clear only the
        // cancellation interrupt.
        //
        // Thread.interrupted();
    }

总结

  • 当任务还未执行Run方法取消后则无法执行该任务
  • 任务已经执行但还没有执行到c.call();则任务也无法执行
  • 任务已经执行(c.call()已经执行),则CANCALED则会让任务继续执行完成,从而调用finishCompletion()方法
  • 任务已经执行(c.call()已经执行),则INTERRUPTING则会让当前线程设置中断标识,状态变为INTERRUPTED。调用finishCompletion()方法

get方法

获取异步执行的结果

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //状态为未启动或者为已完成的中间状态
        if (s <= COMPLETING)
            //等待任务完成
            s = awaitDone(false, 0L);
        return report(s);
    }
	
    /**
         * @throws CancellationException {@inheritDoc}
         */
    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);
    }

    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;
            //已完成(NORMAL、EXCEPTIONAL)或者被取消(CANCALED或中断)
            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);
        }
    }

    private V report(int s) throws ExecutionException {
        Object x = outcome;
        //正常结束 直接返回结果
        if (s == NORMAL)
            return (V)x;
        //当前任务被取消或中断 返回 抛出CancellationException()异常
        if (s >= CANCELLED)
            throw new CancellationException();
        //抛出执行异常
        throw new ExecutionException((Throwable)x);
    }
流程
  1. 判断当前任务有没有完成,如果没有完成则等待任务完成
  2. 判断当前线程有没有被中断,如果被中断了则尝试从等待结果的线程队列里删除该线程,然后抛出InterruptedException()
  3. 线程没有被中断,判断当前任务的状态,如果任务处于已完成(NORMAL、EXCEPTIONAL)或者被取消(CANCALED或中断)则直接返回任务状态
  4. 任务处于COMPLETING(结果赋值)则当前线程放弃CPU后一段实现重新尝试获取任务状态
  5. 如果任务处于运行中,则将该线程放入等待获取结果的队列中,当任务执行完毕后调用finishCompletion()方法将线程唤醒
  6. 根据返回的状态,返回不同的结果。在超时等待获取结果的方法中如果超时后任务还没有完成则直接抛出TimeoutException()

runAndReset()

在不设置结果的情况下执行计算,然后将此 future 重置为初始状态,如果计算遇到异常或被取消,则无法执行此操作。这设计用于本质上多次执行的任务。

    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(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;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值