Runnable,Callable,Future关联浅析


title: Runnable,Callable,Future关联浅析
tags: 面试,小书匠
grammar_cjkRuby: true


Runnable,Callable,Future

Runnable,Callable在ThreadPoolExecutor中的使用

在使用ExecutorService的使用一般会使用submit()方法提交runnable或者callable

看一下AbstractExecutorService中的实现

//java.util.concurrent.AbstractExecutorService
public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);
    execute(ftask);
    return ftask;
}

可以看到都通过newTaskFor()方法生成一个RunnableFuture对象

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return new FutureTask<T>(runnable, value);
}

    
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}

看一下RunnableFuture的构造

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

public FutureTask(Runnable runnable, V result) {
    //包装runnable->callable
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;       // ensure visibility of callable
}

//java.util.concurrent.Executors
public static <T> Callable<T> callable(Runnable task, T result) {
    if (task == null)
    throw new NullPointerException();
    return new RunnableAdapter<T>(task, result);
}

//java.util.concurrent.Executors.RunnableAdapter
//适配器模式 runnable->callable
static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
    RunnableAdapter(Runnable task, T result) {
      this.task = task;
      this.result = result;
    }
    public T call() {
      task.run();
      return result;
    }
}

从上面代码可以看submit(Runnable)和submit(Callable)方法的实现步骤

  1. 判空
  2. 生成RunnableFuture对象
  3. 调用execute()方法
 //java.util.concurrent.ThreadPoolExecutor
 
 //任务队列
 private final BlockingQueue<Runnable> workQueue;
 
 public void execute(Runnable command) {
       ...
       workQueue.offer(command)
       ...
 }

从execute(Runnable)方法签名可以得出: RunnableFuture是个Runnable实现类

FutureTask是RunnableFuture的实现类

看一下FutureTask的继承关系

WX20180304-150947@2x.png

RunnableFuture是一个适配器模式的实现 将Future适配为Runable

看一下FutureTask是如何实现Runnable接口的

 public void run() {
        ...
        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 must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

总结:

  1. ThreadPoolExecutor中的任务队列存放的Runnable对象
  2. 通过execute方法提交的Runable对象会被直接塞到任务队列中
  3. 通过submit(Callable)方法提交的Callable对象会被包装FutureTask对象,再塞到任务队列中
  4. 通过submit(Runnable)方法提交的Runnable会被包装成RunnableAdapter对象(Callable实现),再包成FutureTask对象,再塞到任务队列中

Future

Future:一个异步计算的占位对象,用于获取一个将被计算的结果

WX20180304-153055@2x.png

Future特性:

  1. 通过get()获取一个将被计算的结果
  2. 通过cancel()方法取消对结果的计算

FutureTask.cancel()实现

FutureTask的几种状态

    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;
    
    //可能出现的状态变化过程
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED

cancel实现过程

public boolean cancel(boolean mayInterruptIfRunning) {
        // 1.状态判断 
        // 只有state==New且通过cas修改state值成功 才往下执行 否则return false
        if (!(state == NEW &&
              //状态变化
              // mayInterruptIfRunning? NEW->INTERRUPTING:NEW->CANCELLED
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {//2.打断运行
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // INTERRUPTING->INTERRUPTED
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            //3.结束
            finishCompletion();
        }
        return true;
    }

过程分析:

  1. 状态判断

    if表达式可以拆分成 state == NEW 和 UNSAFE.compareAndSwapInt(this, stateOffset, NEW,mayInterruptIfRunning ? INTERRUPTING : CANCELLED)

    1. state == NEW 判断当前状态是否为NEW

    2. UNSAFE.compareAndSwapInt(this, stateOffset, NEW,mayInterruptIfRunning ? INTERRUPTING : CANCELLED)

      这是一个cas的修改方式 相当于state=mayInterruptIfRunning ? INTERRUPTING : CANCELLED

      cas的方式主要出于线程安全的考虑

      unsafe的用法请自行查阅资料

    总结:如果状态为NEW 且 获取到锁 方可执行真正的cancle操作

  2. 打断运行

    mayInterruptIfRunning?thread.interrupt() : 无操作 ;

  3. 结束

    finishCompletion();

绘图1.png

总结:

  1. 只有state==NEW时才可以进行cancel
  2. 通过unsafe的cas操作修改state
  3. 状态变化两条线
    1. NEW->CANCLE
    2. NEW->INTERRUPTING->INTERRUPTED

FutureTask.run()实现

public void run() {
        // 1.状态判断 
        // 只有state==New且通过cas设置runner值成功 才往下执行 否则return false
        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;
                    //NEW->COMPLETING->EXCEPTIONAL
                    setException(ex);
                }
                if (ran)//NEW->COMPLETING->NORMAL
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
 protected void setException(Throwable t) {
        // 防止cancle()方法修改state
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }
 protected void set(V v) {
        // 防止cancle()方法修改state
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

总结:

  1. 只有state==NEW时方法执行run()过程
  2. 通过unsafe的cas设置runner(当前线程)
  3. 状态变化 两条线:
    1. NEW->COMPLETING->EXCEPTIONAL
    2. NEW->COMPLETING->NORMAL

cancle()总结

  1. 如果run()尚未被执行 则将callable置空且修改状态为非NEW(这样run()方法就不会执行)
  2. 如果run()正在执行且callable.call()尚未执行完成 则调用thread.interrpt()通知线程停止(只是通知 无法保证打断线程 具体原因自行查阅interrpt()资料) 由于cancle修改了state状态 所以setException()和set()无法保存结果
  3. 如果run()执行完毕 或者 callable.call()执行完成 由于 state!=NEW 所以cancle()不继续执行 返回失败

FutureTask.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 (;;) {
            //cancle()过程中调用thread.interrupt()则退出循环 并抛异常
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {//执行完成(包括执行异常) 或被取消 返回当前status
                if (q != null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) //执行完成但尚未修改状态 则Thread.yield()让出cpu资源
                Thread.yield();
            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);
        }
    }
//根据state 返回不同结果
private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

//run()和cancle()最终都会调用finishCompletion() 分析是如何唤醒等待队列中的节点的
private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            // cas方式修改将等待队列置空
            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;        // callable置空
    }

get()总结:

  1. 生成等待节点并加入等待队列中
  2. 通过LockSupport.park() 进行自旋 等待被唤醒
  3. 根据state包装任务执行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容