美文网首页
JUC系列-FutureTask 源码理解

JUC系列-FutureTask 源码理解

作者: 超人也害羞 | 来源:发表于2019-03-21 00:40 被阅读0次

记录自己的学习过程. 共勉.

本次分析的FutureTask源码是基于jdk8的.

一、类继承关系图

分析FutureTask之前,我们先来看看这个类的关系图.它最终是实现了Runnable和Future接口,大概能猜测FutureTask是一个执行线程的实现类并且是有结果的.


FutureTask.png

二、FutureTask 成员变量

我们来看FutureTask源码,首先关注一下它的成员变量.

// FutureTask的状态.
private volatile int state;
/** The underlying callable; nulled out after running */
// 具体执行的任务,初始化时由caller指定.
private Callable<V> callable;
/** The result to return or exception to throw from get() */
/** FutureTask任务的执行结果,可能是Exception*/
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
/** 执行task的线程,只允许一个线程执行.*/
private volatile Thread runner;
/** Treiber stack of waiting threads */
/** 等待task结果的线程栈[Treiber stack算法]*/
private volatile WaitNode waiters;

(1) FutureTask 状态变化
        我认为status成员变量是FutureTask中的一个核心,FutureTask中的设计思路基于status的状态转换,从这个思路入手比较清晰.

/** 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
   */
<!-- COMPLETING状态能不能取消? -->
private volatile int state;

二、状态流转分析

(1) 我们根据statsu的状态流转结合源码进行分析.首先看 NEW -> COMPLETING -> NORMAL,这是一个正常的从task的创建,执行到完成的过程.
a、先看task的创建.

/**
     * 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<V> 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<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        // 利用Executors.callable把runnable 包装成callable,并且自定义result,线程是没有返回值的.
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

任务新建时,status状态是NEW.
b、我们再看实际执行任务的方法,run().(ps:FutureTask本身就是实现了runnable接口)

public void run() {
        // 只有status状态是NEW状态的task才能执行,设置执行task的线程为当前线程.
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            // double check,其他线程会调用cancel(),希望取消任务执行.
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    // 这是真正执行task的代码,只是调用了一下call()方法
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    // 如果任务执行异常,捕获其中抛出的异常信息,修改task的状态为EXCEPTIONAL.并唤醒等待线程.
                    setException(ex);
                }
                if (ran)
                    // 如果任务顺利执行完成,调用set(result)方法,修改其task状态为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;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

set(v)和set(throwable)分别将status设置成了最终的NORMAL和EXCEPTIONAL状态.

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

(2) 上面其实已经分析了 NEW -> COMPLETING -> NORMAL 和 NEW -> COMPLETING -> EXCEPTIONAL 两种情况.接下来,我们聊一聊 NEW -> CANCELLED 和 NEW -> INTERRUPTING -> INTERRUPTED.
a、这两个case都是为了 取消任务.

/**
  * @param mayInterruptIfRunning 是否中断线程,cancel方法会尝试去中断线程,如果你的callable支持中断.
  */
public boolean cancel(boolean mayInterruptIfRunning) {
        // 根据mayInterruptIfRunning判断是直接取消,还是尝试去中断线程.
        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)
                        // 尝试去中断线程,但是具体还是看callable是否支持中断.
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

三、执行结果分析

a、客户端调用get()方法准备获取结果,若任务已完成则直接返回结果,若任务未完成,则阻塞直到任务完成,由任务线程唤醒,或者超时抛出异常.

/**
  * @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 &&
        // awaitDone()如果任务没有完成、取消或者中断,等待结果
        (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
        throw new TimeoutException();
    return report(s);
}

get()主要是调用了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 (;;) {
            // FutureTask支持中断.
            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);
        }
    }

b、我们再来看唤醒等待线程的方法finishCompletion(), 在任务执行完成设置结果时触发, 在状态流转分析小节已经说明了.

/**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out 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;
                        LockSupport.unpark(t); // 唤醒阻塞的等待线程.
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }       
        // 钩子,子类可以自定义. 比如在ExecutorCompletionService类中,利用done()钩子方法把执行完成的task offer到blockingqueue中.
        done();

        callable = null;        // to reduce footprint 帮助gc
    }

c、等待线程被唤醒之后, 在awaitDone()方法中都会调用removeWaiter(q)移除当前的等待线程节点.

    /**
     * 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.
     * 这其实是一个并发情况下利用cas对链表删除节点的操作.
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            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;
            }
        }
    }

~~END

相关文章

网友评论

      本文标题:JUC系列-FutureTask 源码理解

      本文链接:https://www.haomeiwen.com/subject/tpaymqtx.html