FutureTask源码解析

目录

1 成员变量

2 构造方法

3 run 方法

4 set方法

5 finishCompletion方法

6 get方法

7 report方法

8 awaitDone 方法

9 removeWaiter 方法

10 cancel方法


Future 同时 实现了 Runnable 与 Future 接口

不仅是 线程任务 也实现了 异步获取任务结果的能力

 

FutureTask实现的接口信息如下:

Future 接口:

public interface Future {

    /**
     * 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.
     *
     * 

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;

1 成员变量

	/**
     * 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
     */
    /**
     * 当前任务的运行状态。
     *
     * 可能存在的状态转换
     * NEW -> COMPLETING -> NORMAL(有正常结果)
     * NEW -> COMPLETING -> EXCEPTIONAL(结果为异常)
     * NEW -> CANCELLED(无结果)
     * NEW -> INTERRUPTING -> INTERRUPTED(无结果)
     */
     
    //state代表了当前任务的状态的转变:
    //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;  //任务正常完成,结果被set
    private static final int EXCEPTIONAL  = 3;  //任务抛出异常
    private static final int CANCELLED    = 4;  //任务已被取消
    private static final int INTERRUPTING = 5;  //线程中断状态被设置ture,但线程未响应中断
    private static final int INTERRUPTED  = 6;  //线程已被中断

    /** The underlying callable; nulled out after running */
    private Callable callable;  //将要执行的任务
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes  //用于get()返回的结果,也可能是用于get()方法抛出的异常
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;   //执行callable的线程,调用FutureTask.run()方法通过CAS设置
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;  //栈结构的等待队列,该节点是栈中的最顶层节点。

2 构造方法

/**
     * 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 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(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);  //将runnable包装成callable
        this.state = NEW;       // ensure visibility of callable
    }

3 run 方法

    public void run() {
    		//如果state状态不为New或者设置运行线程runner失败则直接返回false,说明线程已经启动过,保证任务在同一时刻只被一个线程执行。
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //2 调用callable.call()方法
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    //如果调用失败抛出异常则执行setException(ex)方法,将state状态设置成EXCEPTIONAL,唤醒所有在get()方法上等待的线程。
                    setException(ex);
                }
                if (ran)
                    //如果调用成功则执行set(result)方法,将state状态设置成NORMAL。
                    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;
            //3.如果当前状态为INTERRUPTING(步骤2已CAS失败),则一直调用Thread.yield()直至状态不为INTERRUPTING
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

4 set方法

    /**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * 

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) { //CAS 更改当前任务的状态 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { //返回值赋值 outcome = v; //把state状态修改成NORMAL,表示现在可以获取返回值。 UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state //最后调用finishCompletion()方法,唤醒等待队列中的所有节点。 finishCompletion(); } }

5 finishCompletion方法

	/**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     */
    //把栈中的元素一个一个弹出,并通过 LockSupport.unpark(t)唤醒每一个节点,通知每个线程,该任务执行完成(可能是执行完成,也可能cancel,异常等)
    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            //通过CAS把栈顶的元素置为null,相当于弹出栈顶元素
            //第一个参数为需要改变的对象,第二个为偏移量(即之前求出来的valueOffset的值),第三个参数为期待的值,第四个为更新后的值。
            //整个方法的作用即为若调用该方法时,value的值与expect这个值相等,那么则将value修改为update这个值,并返回一个true,
            //如果调用该方法时,value的值与expect这个值不相等,那么不做任何操作,并范围一个false。
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    //获取栈顶等待线程
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null; //help gc
                        LockSupport.unpark(t);  //唤醒  通过 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
    }

6 get方法

		/**
     * @throws CancellationException {@inheritDoc}
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //如果state状态小于等于COMPLETING,说明任务还没开始执行或还未执行完成
        if (s <= COMPLETING)
        		//调用awaitDone方法阻塞该调用线程
            s = awaitDone(false, 0L);
        //state的状态大于COMPLETING,则说明任务执行完成,或发生异常、中断、取消状态。
        //直接通过report方法返回执行结果
        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;
        //还未完成  且 超时时间<=1
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            //超时直接抛出TimeoutException异常
            throw new TimeoutException();
        return report(s);
    }

7 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;
        // 正常完成  将Object强转为泛型 返回
        if (s == NORMAL)
            return (V)x;
        // 成功取消执行、或响应中断 抛出取消异常
        if (s >= CANCELLED)
            throw new CancellationException();
        //抛出其他异常
        throw new ExecutionException((Throwable)x);
    }

8 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();
            }
						//获取当前future状态
            int s = state;
            //如果state状态大于COMPLETING 则说明任务执行完成,或取消
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //如果state=COMPLETING,则使用yield,因为此状态的时间特别短,通过yield比挂起响应更快。
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();// 新的等待节点
            else if (!queued)
                //cas节点入队列  失败重试
                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);
        }
    }

9 removeWaiter 方法

		/**
     * Tries to unlink a timed-out or interrupted wait node to avoid
     * accumulating garbage.  Internal nodes are simply unspliced
     * without CAS since it is harmless if they are traversed anyway
     * by releasers.  To avoid effects of unsplicing from already
     * removed nodes, the list is retraversed in case of an apparent
     * race.  This is slow when there are a lot of nodes, but we don't
     * expect lists to be long enough to outweigh higher-overhead
     * schemes.
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null; //标识要被移出的waiter
            retry:
            for (;;) {          // restart on removeWaiter race
                //从头结点开始遍历
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    //下一个循环节点
                    s = q.next;
                    if (q.thread != null) //为null  当前q就是要被移出的waiter
                        pred = q;
                    else if (pred != null) {  //q.thread==null,当前节点已无效且有前驱,则将前驱的后继置为当前节点的后继实现删除节点。
                        pred.next = s;
                        if (pred.thread == null) // check for race  //如果前驱节点已无效,则重新遍历waiters栈。
                            continue retry;
                    }
                    /*
                     * 当前节点已无效,且当前节点没有前驱,则将栈顶置为当前节点的后继。
                     * 失败的话重新遍历waiters栈。
                     */
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

10 cancel方法

    public boolean cancel(boolean mayInterruptIfRunning) {
    		/*
         * 在状态还为NEW的时候,根据参数中的是否允许传递,
         * 将状态流转到INTERRUPTING或者CANCELLED。
         */
        //根据mayInterruptIfRunning是否为true,CAS设置状态为INTERRUPTING或CANCELLED,设置成功,继续第二步,否则返回false
        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();  //如果mayInterruptIfRunning为true,调用runner.interupt(),设置状态为INTERRUPTED
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            //唤醒所有在get()方法等待的线程   任务已经被中断 或取消啦 大家都醒醒吧~
            finishCompletion();
        }
        return true;
    }

 

你可能感兴趣的:(JUC)