FutureTask 源码解读

FutureTask 是一个很简单的类。贴点代码,写点注释把。

构造函数传入一个callable对象,或则runable对象,runable对象的返回类型为Void的泛型。

主要成员变量如下:

private volatile int state;                    //FutureTask当前的状态
private Callable<V> callable;                  //构造函数传入的callable对象
/** The result to return or exception to throw from get() */
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 */
private volatile WaitNode waiters; //维护了一个等待队列

主要有2个方法:run 和get

run 执行了callable得到和设置结果,并唤醒等待队列。

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(); // 这里调用了callable的call方法,并得到返回结果
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);   //设置了outcome值,并且调用了finishCompletion
            }
        } finally {
            runner = null;
            int s = state; //以下处理中断等等
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s); 
        }
    }
    
    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) { //将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方法,如果结果还没有计算好:将当前线程加入到等待队列,并且阻塞当前线程。如果计算完毕,就直接返回结果。

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)  //未完成就排队。
            s = awaitDone(false, 0L);  
        return report(s);
    }

 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();   //第一次循环, 实例化一个等待的WaitNode
            else if (!queued)         //第二次, 将自己加入等待队列,可能会多次(如果很多线程一起获取)。
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {         //第三次,将线程park,如果是timed,就是带时间的park。
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
    }


你可能感兴趣的:(FutureTask 源码解读)