[JUC源码剖析]__FutureTask类

FutureTask类

先看下FutureTask类的继承图,它同时实现了Future类和Runnable类,也就是说它实际上是可以被当做一个Runable传给Thread类执行的
[JUC源码剖析]__FutureTask类_第1张图片

由FutureTask的构造方法可以看到,该类需要一个Callable接口来初始化

    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

回顾上一篇文章JUC源码剖析__ThreadPoolExecutor,当向线程池submit一个Callable对象时,AbstractExecutorService.submit会使用Callable创建一个FutureTask实例,线程池的Worker线程最终会执行这个FutureTask的Runnable.run方法

FutureTask.get方法最终是怎么获取到Callable.call的返回值的?

先来看看FutureTask.get方法的源码

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        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);
    }

当状态小于等于COMPLETING时,则阻塞线程等待完成;否则就调用report返回FutureTask的outcome字段。也就是说FutureTask最终会把结果保存在outcome字段中

FutureTask是怎么把callable的结果保存到outcome字段中的呢?

之前的文章提到过线程池的Worker线程最终会执行这个FutureTask的Runnable.run方法

 public void run() {
        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 {
                    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);
        }
    }
    //为了方便起见把 outcome字段的定义写在这里
    private Object outcome; // non-volatile, protected by state reads/writes
    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

可以看到当调用Callable.call方法返回结果后,会执行set(result)把结果set进outcome字段中
这里刚开始看的时候觉得很奇怪:

  • 为什么outcome字段没有设置成volatile?
  • 为什么在outcome = v;前要把状态设置成COMPLETING,而outcome = v;完后又立刻把状态设置成NORMAL呢?

直到网上找到了这篇文章why outcome object in FutureTask is non-volatile?

这里有个很巧妙的设计,就是利用java的happends before中的传递原则,使得在不使用锁的情况下,保证其他线程读到state=NORMAL时,该线程一定能读到outcome的最新值

当Future.get方法阻塞时,当完成任务后是怎么唤醒阻塞线程的?

文章开头提到过,调用FutureTask.get方法时,当状态小于等于COMPLETING时,则阻塞线程等待完成

/** Treiber stack of waiting threads */
private volatile WaitNode waiters;

static final class WaitNode {
    volatile Thread thread;
    volatile WaitNode next;
    WaitNode() { thread = Thread.currentThread(); }
}

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

又是一个自旋操作,值得一提的是这段代码:

 else if (s == COMPLETING) // cannot time out yet
                Thread.yield();

这个判断其实是为了处理protected void set(V v)中的临时状态的,当FutureTask出现COMLETING状态时,其实任务已经执行完了,只不过是在保存结果时发生了线程切换,所以只要很短暂的等待就可以,这里使用Thread.yield()让出线程的执行权

当第一次循环时,如果任务还没有处理完,则会新建一个WaitNodeWaitNode中保存了当前线程;
当第二次循环时,如果任务还没有出来完,则会把这个WaitNode插入到waiters的栈顶,并通过调用LockSupport.parkNanos或者LockSupport.park阻塞当前线程。而唤醒线程就是通过waiters栈中元素保存的Thread来唤醒。这里可以发现,如果有多个线程都调用FutureTask.get方法且都阻塞的话,则线程会按调用顺序插入waiters栈中

如何通过WaitNode唤醒阻塞的线程?
protected void set(V v)中保存callable的结果后会调用private void finishCompletion()方法,程序就是通过这个方法来把waiters栈中的阻塞线程按照后进先出的顺序来逐个调用LockSupport.unpark释放掉

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
    }

参考

why outcome object in FutureTask is non-volatile?

你可能感兴趣的:(java,源码分析,多线程)