FutureTask源码分析

1. 常量和变量

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;
// run正常执行:NEW -> COMPLETING -> NORMAL
// run异常执行:NEW -> COMPLETING -> EXCEPTIONAL
// cancel(false):NEW -> CANCELLED
// cancel(true):NEW -> INTERRUPTING -> INTERRUPTED

private Callable<V> callable; // 任务
private Object outcome; // 执行结果
private volatile Thread runner; // 任务执行线程(在run方法中置为当前线程)
private volatile WaitNode waiters; // 任务等待链表(头节点)

2. 构造方法

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

public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result); // RunnableAdapter implements Callable
    this.state = NEW;
}

3. 等待节点

static final class WaitNode {
    volatile Thread thread; // 等待线程
    volatile WaitNode next; // 下一等待节点
    WaitNode() { thread = Thread.currentThread(); }
}

4. 实现Future接口

1)cancel

public boolean cancel(boolean mayInterruptIfRunning) {
    // 任务状态为NEW && CAS设置state = INTERRUPTING || CANCELLED
    if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
        return false;
    try {
        if (mayInterruptIfRunning) { // 允许在任务执行时被中断
            try {
                Thread t = runner;
                if (t != null) // 任务尚未执行完毕
                    t.interrupt(); // 中断任务所在线程
            } finally {
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // state = INTERRUPTED
            }
        }
    } finally {
        finishCompletion(); // 唤醒所有等待任务执行结果的线程(见get和awaitDone方法)
    }
    return true;
}

private void finishCompletion() {
    for (WaitNode q; (q = waiters) != null;) { // 从头节点(q)开始遍历waiters链表
        if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { // CAS设置waiters链表为空
            for (;;) {
                Thread t = q.thread;
                if (t != null) {
                    q.thread = null; // 标记节点q被唤醒
                    LockSupport.unpark(t); // 唤醒线程
                }
                WaitNode next = q.next;
                if (next == null)
                    break;
                q.next = null;
                q = next;
            }
            break;
        }
    }
    done(); // noop
    callable = null;
}

protected void done() { }

2)isCancelled和isDone

public boolean isCancelled() { // 任务是否已取消执行
    return state >= CANCELLED;
}

public boolean isDone() { // 任务是否执行完毕(对外如此,对内是 <= COMPLETING)
    // cancel方法直接设置任务状态为INTERRUPTING || CANCELLED,run方法中在set执行结果时设置任务状态为COMPLETING
    return state != NEW;
}

3)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;
    // 在timeout时间内等待
    if (s <= COMPLETING && (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
        throw new TimeoutException();
    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) // 任务执行中
            Thread.yield();
        else if (q == null) // 任务尚未执行(s == NEW),则建立任务等待节点q
            q = new WaitNode();
        else if (!queued) // q尚未排队,则CAS设置q为头节点
            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); // 在naos时间内等待
        }
        else
            LockSupport.park(this); // 永久等待
    }
}

private void removeWaiter(WaitNode node) {
    if (node != null) {
        node.thread = null;
        retry:
        for (;;) {
            // pred被唤醒 || CAS(waiters)失败:回到此处
            for (WaitNode pred = null, q = waiters, s; q != null; q = s) { // 从头节点(q)开始遍历waiters链表
                s = q.next;
                if (q.thread != null) // q未被唤醒
                    pred = q;
                else if (pred != null) { // q已被唤醒 && q前存在未被唤醒节点
                    pred.next = s; // 在链表中删除p
                    if (pred.thread == null) // pred被唤醒(其它线程正在同步finishCompletion:cancel || run) || pred超时(其它线程正在同步removeWaiter)
                        continue retry;
                }
// q已被唤醒 && q前不存在未被唤醒节点,则CAS设置头节点为q.next
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset, q, s)) continue retry; } break; } } }

5. 实现Runnable接口

public void run() {
    // 任务未开始执行 || CAS设置runner = Thread.currentThread失败
    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); // 任务可能正在被其它线程cancel:等待cancel的完成
    }
}

protected void set(V v) {
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { // CAS设置state = COMPLETING(任务可能已被cancel)
        // CAS(state)成功
        outcome = v;
        UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // state = NORMAL
        finishCompletion(); // 唤醒所有任务等待节点
    }
}

protected void setException(Throwable t) {
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { // CAS设置state = COMPLETING(任务可能已被cancel)
        // CAS(state)成功
        outcome = t;
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // state = EXCEPTIONAL
        finishCompletion(); // 唤醒所有任务等待节点
    }
}

private void handlePossibleCancellationInterrupt(int s) {
    if (s == INTERRUPTING)
        while (state == INTERRUPTING)
            Thread.yield();
}

6. Unsafe

private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
    try {
        UNSAFE = sun.misc.Unsafe.getUnsafe();
        Class<?> k = FutureTask.class;
        stateOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("state"));
        runnerOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("runner"));
        waitersOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("waiters"));
    } catch (Exception e) {
        throw new Error(e);
    }
}
posted @ 2017-12-24 23:23  Uncle_Bjorney  阅读(161)  评论(0编辑  收藏  举报