• FutureTask分析(1.8)


    FutureTask简介

    FutureTask用于异步计算,也就是支持异步执行并返回结果。FutureTask本身是一个Runable,所以可以交给Thread来运行,在提交给Thread运行后,可以有多个线程调用get来等待计算结果,并支持超时等待,同时支持cancel操作用于取消一个正在运行的FutureTask。

    数据结构定义

    FutureTasks实现了RunnableFuture接口,RunnableFuture扩展了Runnable和Future接口。

    FutureTask内部定义了一个state来指示当前的运行状态,state会被多个线程同时修改,内部并没有使用锁来保证线程安全,而是使用了volatile和CAS。对state最终状态进行修改还是用了putOrderedInt这样的操作来做延迟写入(禁止重排序,但是不会加lock add flush缓存)。

    由于支持多个线程同时进行get操作,所以内部定义了一个Treiber stack(无锁,线程安全)来保存所有在get上等待的线程,在计算完成后,会从头到尾逐个唤醒这些线程。

    public class FutureTask<V> implements RunnableFuture<V> {
        /**
         * The run state of this task, initially NEW.  The run state
         * transitions to a terminal state only in methods set,
         * setException, and cancel.  During completion, state may take on
         * transient values of COMPLETING (while outcome is being set) or
         * INTERRUPTING (only while interrupting the runner to satisfy a
         * cancel(true)). Transitions from these intermediate to final
         * states use cheaper ordered/lazy writes because values are unique
         * and cannot be further modified.
         *
         * Possible state transitions:
         * 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;
    
        //callable是计算结果的代码块
        private Callable<V> callable;
        //callable的计算结果保存在这,这个字段不是volatile的,由state的读写来保护
        private Object outcome; 
        //运行的线程
        private volatile Thread runner;
        //等待结果的队列
        private volatile WaitNode waiters;
    }
    

    实例化FutureTask

    构造FutureTask需要传入一个callable。

        public FutureTask(Callable<V> callable) {
            if (callable == null)
                throw new NullPointerException();
            this.callable = callable;
            this.state = NEW;       // 确保callable的可见性,因为state是volatile修饰的,
        }
    

    执行Callable

    Callable需要在线程上异步执行,所以FutureTask实现了Runnable接口,在run方法里面来执行Callable来获取结果。run方法步骤如下:

    1. 判断状态是否能执行
    2. 执行callable,如果成功set结果,如果失败set异常。
    3. 最后判断是否外部线程发起了终端请求,如果是,则等待中断完成。
        public void run() {
            //确保task不会被重复执行
            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 {
                        //执行callable的call方法获取结果
                        result = c.call();
                        ran = true;
                    } catch (Throwable ex) {
                        result = null;
                        ran = false;
                        setException(ex);
                    }
                    if (ran)
                        set(result);
                }
            } finally {
                runner = null;
                //线程运行时已经接收到了中断请求,测试state为INTERRUPTING状态,需要确保state
                //变成INTERRUPTED状态。INTERRUPTING->thread.interrupt()->INTERRUPTED
                int s = state;
                if (s >= INTERRUPTING)
                    handlePossibleCancellationInterrupt(s);//内部自旋使用Thread.yeild()
            }
        }
    

    Callable执行完成后,需要设置结果,并唤醒所有等待取结果的线程,state会被先cas设置成COMPLETING,如果成功则设置结果,并将最终状态设置成NORMAL。最后调用finishCompletion来唤醒所有等待线程。

        protected void set(V v) {
            //如果当前状态是NEW,则设置成COMPLETING
            if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
                //设置结果
                outcome = v;
                //设置最终状态
                UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
                //唤醒等待取结果的线程
                finishCompletion();
            }
        }
    

    唤醒等线程

        private void finishCompletion() {
            // assert state > COMPLETING;
            //循环尝试将waiters设置成null,如果成功,则开始进行遍历,唤醒线程。
            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;
                }
            }
            //执行一个protect的空方法,这个方法主要是用于子类扩展,CompletionService就使用了
            //这个方法将计算结果放入BlockingQueue。
            done();
    
            callable = null;        // to reduce footprint
        }
    

    获取异步计算结果

    使用get方法获取一个异步计算的结果,如果计算已经完成,那么立刻返回这个结果,否则线程需要挂起等待计算完成后被唤醒。如果get设置了超时时间,那么可能会因为超时被唤醒。get内部都使用了awaitDone方法。这个方法的核心就是一个自旋for(;;),终止条件是当前线程被中断,或者task执行完成了,或者等待超时了。

    awaitDone方法的编程模式比较奇怪,其实核心思想是尽量自旋以阻止线程被挂起。因此在执行每行代码时候都会做必要的检查。尽量不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;
                }
                //计算已经COMPLETING,接下很短的时间会被设置成NORMAL(纯CPU计算,无等待),并唤醒等待线程
                //所以这里使用了Thread.yield () 尝试让出线程调度资源,而不是去挂起线程。
                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);
            }
        }
    

    removeWaiter将节点从队列中移除。由于不加锁,这个方法显然也是自旋+CAS,基本步骤是:

    • 首先将要移除节点的thread设置成null
    • 遍历链表将thread为null的节点移除
        private void removeWaiter(WaitNode node) {
            if (node != null) {
                node.thread = null;
                retry:
                for (;;) {          // restart on removeWaiter race
                    //pred前驱节点,q当前节点,s后继结点
                    for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                        s = q.next;
                        //thread不为null,说明是有效节点,更新前驱节点继续后移
                        if (q.thread != null)
                            pred = q;
                            
                        //thread为null,需要将p节点移除,
                        else if (pred != null) {
                            //移除p节点
                            pred.next = s;
                            //判断pred节点的thread是否为null,如果为null,说明pred节点可能被
                            //另一个线程移除了。那么pred显然是已经脱离了链表,上一步的操作
                            //是无效的,需要从链表头部重新遍历。
                            if (pred.thread == null) // check for race
                                continue retry;
                        }
                        
                        //要移除的节点是头结点,CAS将后继结点设置成头。如果失败,说明链表结构
                        //发生了变化,需要从链表头部重新遍历。
                        else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                              q, s))
                            continue retry;
                    }
                    
                    //遍历到了尾部,break
                    break;
                }
            }
        }
    

    取消任务执行

    FutureTask支持取消操作,但是只能取消NEW状态的Task,处于NEW状态的Task可能线程已经启动了,但是还没完成计算。可以指定mayInterruptIfRunning=true,强制将线程中断,否则将忽略执行线程,执行线程可能会继续运行,直到结束。

        public boolean cancel(boolean mayInterruptIfRunning) {
            if (state != NEW)
                return false;
            if (mayInterruptIfRunning) {
                if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                    return false;
                //设置INTERRUPTING成功,开始中断线程。
                Thread t = runner;
                if (t != null)
                    t.interrupt();
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
            }
            else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
                return false;
                
            //取消成功,唤醒所有等待get的线程
            finishCompletion();
            return true;
        }
    
  • 相关阅读:
    十步完全理解SQL
    c#退出应用程序办法
    几个有意思的算法题
    GeoServer不同服务器安装配置、数据发布及客户端访问
    开启httpd服务的时候 显示Could not reliably determine the server`s fully qualified domain name
    Working With OpenLayers(Section 1: Creating a Basic Map)
    GeoServer地图开发解决方案(五):基于Silverlight技术的地图客户端实现
    模拟远程HTTP的POST请求
    模拟提交带附件的表单
    支付宝手机网站接口对接
  • 原文地址:https://www.cnblogs.com/techspace/p/7080522.html
Copyright © 2020-2023  润新知