并发编程工具集——Callable 任务如何运行以及获取执行结果-下篇(三十二)

提接上文~~重点来了!再跟进去看看runWoker是何方神圣:

//java.util.concurrent.ThreadPoolExecutor#runWorker
final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;//task 实际上是FutureTask类型的对象
        w.firstTask = null;
        try {
            while (task != null || (task = getTask()) != null) {
              //省略一些 非关键代码....
                try {
                    beforeExecute(wt, task);//
                    try {
                        //重点代码!触发 java.util.concurrent.FutureTask#run 执行
                        task.run();
                        afterExecute(task, null);
                    } catch (Throwable ex) {
                        //去看看afterExecute方法注释,无论线程执行过程中是否抛异常,afterExecute()都会 执行,看了源码,明白为什么是这样了,因为catch异常处理里面会执行afterExecute
                        afterExecute(task, ex);
                        throw ex;
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }

看懂了java.util.concurrent.ThreadPoolExecutor#runWorker几乎就明白线程池执行任务时的beforeExecute、afterExecute方法的所起的作用了(比如经常在afterExecute方法里面做一些线程池任务运行时间的统计工作)。

总结以下点:

  • Callable任务被submit时,会生成一个FutureTask对象,封装Callable,在FutureTask的run方法里面执行Callable#call方法,并且调用java.util.concurrent.FutureTask#set设置Callable任务的执行结果(结果保存在一个FutureTask的Object类型的实例变量里面:private Object outcome;)。

  • Future<Integer> future = executorService.submit(callable);返回一个Future,它实际上是一个FutureTask对象,通过java.util.concurrent.FutureTask#get()获取Callable任务的执行结果。

  • java.util.concurrent.FutureTask#run方法是由java.util.concurrent.ThreadPoolExecutor#runWorker触发调用的;而java.util.concurrent.ThreadPoolExecutor#runWorker又是由java.util.concurrent.ThreadPoolExecutor.Worker#run触发调用的;而java.util.concurrent.ThreadPoolExecutor.Worker#run又是由java.util.concurrent.ThreadPoolExecutor#addWorker里面的t.start();这条语句触发调用的;而t.start();会触发Runnable#run方法的执行。这就是前面提到的这个原理:new Thread(Runnable).start()会由jvm来调用Runnable#run。具体可参考:

  • 继承 ThreadPoolExecutor 实现自定义的线程池时,可重写 afterExecute()方法做一些异常处理逻辑的实现,不管任务正常执行完成、还是抛出异常,都会调用afterExecute(),具体可看JDK源码关于ThreadPoolExecutor#runWorker方法的注释。有兴趣可研究下ES SEARCH线程池源码就使用afterExecute来统计提交给线程池的每个任务的等待时间、执行时间,从而根据Little's law 自动调整线程池任务队列的长度:org.elasticsearch.common.util.concurrent.QueueResizingEsThreadPoolExecutor#afterExecute

最后,想说的是:Callable任务,到ThreadPoolExecutor线程池执行 层面,它实际上是一个Runnable任务在执行。因为,ExecutorService submit Callable时,其实是将Callable封装到FutureTask/RunnableFuture中,而RunnableFuture implements Runnable,因此可以提交给线程池的java.util.concurrent.ThreadPoolExecutor#execute(Runnable command)执行,这就回答了本文开头提出的第二个问题。

//java.util.concurrent.RunnableFuture
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

用一张图表示就是:

Callable任务的设置与获取,则都是在FutureTask这个层面上完成,把Callable封装到FutureTask中,而FutureTask implements Runnable,从而转化成ThreadPoolExecutor#execute执行Runnable任务。

Callable任务的执行结果又是怎么获取的?Future.get为什么会阻塞?

java.util.concurrent.FutureTask 的private volatile int state;变量:

//java.util.concurrent.FutureTask#run
public void run() {
        if (state != NEW ||
            !RUNNER.compareAndSet(this, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //Callable#call执行成功, ran=true
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //ran=true,才会设置Callable任务的执行结果
                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);
        }
    }

set方法设置Callable任务的执行结果时,会修改 FutureTask的 state 实例变量的值!

	//java.util.concurrent.FutureTask#set   
	protected void set(V v) {
        if (STATE.compareAndSet(this, NEW, COMPLETING)) {
            outcome = v;
            STATE.setRelease(this, NORMAL); // final state
            finishCompletion();
        }
    }

java.util.concurrent.FutureTask#get()方法,也正是通过检查 state 的值,来确定是否能够拿到Callable任务的执行结果。

    //java.util.concurrent.FutureTask#get()
	public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            //如果 state 不是在 NORMAL 状态,FutureTask#get()就会阻塞
            //这就是 java.util.concurrent.Future#get() 阻塞的原因
            s = awaitDone(false, 0L);//这里面会调用:Thread.yield()、LockSupport.park(this)
        return report(s);
    }

java.util.concurrent.FutureTask#awaitDone

//java.util.concurrent.FutureTask#awaitDone
private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
    	WaitNode q = null;
		//省略一些无关代码...
        for (;;) {//for循环一直检查任务的运行状态....直到可以"结束"
            int s = state;
            //state的值大于 COMPLETING 说明已经有Callable任务的结果了
            //java.util.concurrent.FutureTask#set 设置了Callable任务的结果,修改了state的值
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //COMPLETING 任务的运行状态是:正在执行中
            else if (s == COMPLETING)
                // We may have already promised (via isDone) that we are done
                // so never return empty-handed or throw InterruptedException
                Thread.yield();//挂起获取执行结果的线程(这就是Futur#get阻塞的原因)
            else if (Thread.interrupted()) {
                removeWaiter(q);//任务可能被中断了,当然就不需要等待获取执行结果了
                throw new InterruptedException();
            }
            else if (q == null) {
                if (timed && nanos <= 0L)
                    return s;
                q = new WaitNode();
            }
            else if (!queued)
                queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
            //java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)超时阻塞的实现原理
            else if (timed) {
                final long parkNanos;
                if (startTime == 0L) { // first time
                    startTime = System.nanoTime();
                    if (startTime == 0L)
                        startTime = 1L;
                    parkNanos = nanos;
                } else {
                    long elapsed = System.nanoTime() - startTime;
                    if (elapsed >= nanos) {
                        removeWaiter(q);
                        return state;
                    }
                    parkNanos = nanos - elapsed;
                }
                // nanoTime may be slow; recheck before parking
                if (state < COMPLETING)
                    LockSupport.parkNanos(this, parkNanos);
            }
            else
                LockSupport.park(this);
        }
    }

总结一下:通过 state变量来判断Callable任务的执行结果是否已经生成。如果已经生成了执行结果,那么 java.util.concurrent.FutureTask#set会把结果放到private Object outcome;outcome这个变量中。然后设置state的值为NORMAL,那么java.util.concurrent.FutureTask#get()通过检查 state 的值,就能拿到执行结果了,当然了,如果执行结果还未生成,java.util.concurrent.FutureTask#awaitDone就会导致 get 阻塞。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值