FutureTask详解

300 阅读2分钟

众所周知,java执行线程只有两周种方式

  1. 继承Thread类重写run方法
  2. 实现runnable接口,丢到thread中

FutureTask

首先来看看继承类图 image.png 实现了Runnable说明可以丢到线程中执行.并且实现了 Future 说明可以拿到线程执行的返回值. 通过源码看看内部是如何实现的

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

    # futureTask 状态
    private volatile int state;
    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

    # 内部有一个callable对象
    private Callable<V> callable;
    # callable执行的结果储存
    private Object outcome; // non-volatile, protected by state reads/writes
    # 执行异步任务的线程
    private volatile Thread runner;
    # 存储调用get方法阻塞的线程队列
    private volatile WaitNode waiters;



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


    # 获取结果的方法,调用了 awaitDone
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }


    # 在异步任务中执行 callable 的call方法,将结果保存到 outcome属性中
    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 = null;
 
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

    # 等待队列,所有调用了get方法的线程都会被封装成一个 WaitNode
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

    # 找到等待队列,调用 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
    }

    # 当调用了 get方法后最终会执行到这里,本职也是一个cas的操作
    # 会将当前线程封装成一个 node 存入等待队列中,然后 park住,被唤醒之后
    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)
                # 封装node
                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);
        }
    }

}

FutureTask 的源码很简单,就是继承了 Runnable然后保存Callable实现结果的存储.

image.png