线程工具类FutureTask

FutureTask官方文档

java中可以通过继承Thread或者实现Runnable接口来实现多线程,但是这种方式并不能让我们在线程执行完后获取执行结果。因此在java1.5开始引入了Callable和Future接口,通过它们可以在线程执行完后获取执行结果。Callable表示一个可返回结果的任务,Future表示一个异步计算的结果

FutureTask的实现只是依赖了一个内部类Sync实现的,Sync是AQS (AbstractQueuedSynchronizer)的子类,这个类承担了所有future的功能,AbstractQueuedSynchronizer的作者是大名鼎鼎的并发编程大师Doug Lea。

1.类声明

public class FutureTask<V> implements RunnableFuture<V>

FutureTask实现了RunnableFutute接口,RunnableFutute实际上是一个组合接口,由Runnable接口和Future接口组合而成。

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

@FunctionalInterface
public interface Runnable {
    /**
     * Sets this Future to the result of its computation unless it has been cancelled.
     */
    public abstract void run();
}

public interface Future<V> {

    //试图取消对此任务的执行。
    boolean cancel(boolean mayInterruptIfRunning);

    //如果在任务正常完成前将其取消,则返回 true。
    boolean isCancelled();

    //如果任务已完成,则返回 true。
    boolean isDone();

    //如有必要,等待计算完成,然后获取其结果。
    V get() throws InterruptedException, ExecutionException;

    //如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

这里有个值得玩味的地方是:既然RunnableFuture已经继承了Runnable接口,为什么还要再声明一个run()方法?StackOverFlow网站上也有这个问题:Why does java.util.concurrent.RunnableFuture have a run() method? 。点赞最多的答案已经给了我们答复:仅仅是因为jdk的开发者想给run()方法加上新的Doc注释,所以就显式的重新声明一个run()方法,并没有任何技术相关的含义。

2.属性

    private volatile int state;
    //初始状态
    private static final int NEW          = 0;
    //任务即将结束状态。该状态是个瞬时状态,之后会进入NORMAL状态或EXCEPTIONAL状态。当结果值outcome被设置后出现该瞬时状态。
    private static final int COMPLETING   = 1;
    //任务正常结束状态。
    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;
    //任务被中断结束状态。
    private static final int INTERRUPTED  = 6;

    /** The underlying callable; nulled out after running */
    //底层的Callable任务。任务运行结束后会被设置为null。
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    //任务执行结果:调用get()方法时,返回的结果或者抛出的异常结果。【非volatile,被state的读写方法进行保护】
    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 */
    //等待节点(Treiber栈结构)
    private volatile WaitNode waiters;

等待节点使用了Treiber Stack数据结构。

任务的运行总共有如下7种状态:

  • NEW:0。任务的初始状态
  • COMPLETING:1。任务即将完成状态。该状态是个瞬时状态,之后会立即进入NORMAL状态或EXCEPTIONAL状态。当结果值outcome被设置后出现该瞬时状态。
  • NORMAL:2。任务正常完成状态。
  • EXCEPTIONAL:3。任务出现异常状态。
  • CANCELLED:4。任务被取消的状态。
  • INTERRUPTING:5。任务正被中断状态。也是一个瞬时状态,调用cancel(true)取消任务时会出现该瞬时的正被中断状态。
  • INTERRUPTED:6。任务被中断状态。

运行状态仅能通过set,setException和cancel方法进行改变。可能发生的状态流转有如下4种情况:

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

用画图表示更一目了然。

3.创建任务

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

我们使用FututeTask通常用来异步执行并获取结果,有执行结果的任务用Callable表示。

4.提交任务

任务需要通过线程或线程池来执行。无论是线程,还是线程池,最后都是会调用线程的start方法来执行任务的。而start方法会调用Thread的run方法,最终执行的是传入的任务的run()方法,也就是FutureTask的run方法,来简单分析一下。通过将FutureTask实例传递给Thread来执行的。

//该处target代表FututeTask实例
new Thread(target).start();

跟踪一下Thread的源码:Thread内部也有个target属性,上面的Thread构造器最终会将FutureTask实例传递给Thread中的target。再来看看Thread的run()方法,执行的就是传入实例的run方法。

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

5.执行任务-run

执行任务

经过上面的分析,既然线程执行的是FutureTask的run方法,那就来跟踪一下吧。

    public void run() {
        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()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

处理取消中断

    /**
     * Ensures that any interrupt from a possible cancel(true) is only
     * delivered to a task while in run or runAndReset.
     */
    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)
            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();
    }

6.取消任务-cancel

6.1取消任务

    public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

执行该取消操作的线程与任务执行线程自然不是同一个线程。取消任务时,可以同时给任务执行线程下达中断通知,当然也可以不下达,这是通过参数mayInterruptIfRunning来控制的。想想线程池的场景,当取消任务时,线程池中的线程可以继续存活,或者调用者希望将其中断掉。

①如果mayInterruptIfRunning为true,表示取消任务,同时中断任务执行线程。

  • 将任务从NEW状态设置为INTERRUPTING瞬时状态,并给任务执行线程下达中断通知,之后将任务状态设置为INTERRUPTED状态。而执行任务的线程检测到中断后,就会响应中断。

②如果mayInterruptIfRunning为false,表示取消任务,但不中断任务执行线程。

  • 则将任务状态从New设置为INTERRUPED状态。

完成上面的操作后,会唤醒等待线程(finishCompletion)

6.2唤醒等待线程-finishCompletion

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

        done();

        callable = null;        // to reduce footprint
    }

7.获取任务执行结果-get

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

Treiber Stack数据结构

FututeTask的等待节点是一个Treiber Stack结构。Treiber Stack在 R. Kent Treiber1986年的论文Systems Programming: Coping with Parallelism中首次出现。 

可以参考相关文章:

Treiber Stack简单分析

FutureTask中的waiters为什么这么设计?

Treiber Stack - Wikipedia

总结

1.Callable和Future代表的含义?

2.Future和FutureTask的区别?

2.FutureTask的应用场景?

原文地址:https://www.cnblogs.com/rouqinglangzi/p/7874769.html