JDK源码(FutureTask)——java.util.concurrent(十)

测试代码:
https://github.com/kevindai007/springboot_houseSearch/tree/master/src/test/java/com/kevindai/juc

今天咱们一起来学习一下FutureTask,FutureTask实现RunnableFuture,RunnableFuture又继承Runable和Future,因此FutureTask即是Runable又是Future

下面咱们看看FutureTask的一些主要属性

    /**
     * 线程间存在的转换关系
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    //线程状态
    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;
    //要执行的任务
    private Callable callable;
    //返回结果
    private Object outcome;
    //执行任务的线程
    private volatile Thread runner;
    //单向等待链表
    private volatile WaitNode waiters;

    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;
    }
    public FutureTask(Runnable runnable, V result) {
        //调用Executors的callable()方法,把runnable构造成callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW; 
    }

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

咱们再来看看其主要方法

    public void run() {
        //状态不为NEW或者给runner赋值失败就直接返回
        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 = null;
            int s = state;
            //处理线程中断
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

    //此方法与run()方法类似,区别在于此方法不会设置任务的执行结果,最后返回是否正确的执行并复位
    protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable c = callable;
            if (c != null && s == NEW) {
                try {
                    //注意这里的区别,这里没有设置返回值
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } finally {
            runner = null;
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        // 是否正确的执行并复位
        return ran && s == NEW;
    }

看看上面用到的线程正常执行的set()、异常的setException()

    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //设置结果
            outcome = v;
            //更改状态
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            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
    }

    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

再来看看get()

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //线程还没有执行完
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        //获取返回结果
        return report(s);
    }
    //会等待超时的get()
    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);
    }

get()其实很简单,如果线程没有执行完就加入链表等待,否则就返回(设置过超时时间会判断是否超时)

    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();
            //首次循环一般会进入这里,创建一个WaitNode
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                // CAS设置栈顶节点
                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);
        }
    }

    //移除等待的节点
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            //自旋保证移除节点成功
            for (;;) {
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    //q.thread != null说明该q节点不需要移除
                    if (q.thread != null)
                        pred = q;
                    //如果q.thread == null,且pred != null,需要删除q节点
                    else if (pred != null) {
                        pred.next = s;
                        //pred.thread == null时说明在并发情况下被其他线程修改了
                        //返回第一个for循环重试
                        if (pred.thread == null)       
                             continue retry;
                    }
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                break;
            }
        }
    }

到这里主要的方法都看完了,咱们做个简单的总结:
FutureTask的运行的基本流程如下

  1. submit一个task,获的返回的Future:提交task后,就是ThreadPoolExecutor的那一套流程addworker-runwork-gettask-task.run,最后会到提交的task的run()方法
  2. 通过Future的get()获取执行的结果
  3. 也可以cancel()方法取消未执行的task

你可能感兴趣的:(jdk源码)