ExecutorService中的awaitTermination“发生在之前”任何代码执行后呢? [英] Does awaitTermination in ExecutorService "happens-before" any code executed after it?

查看:3957
本文介绍了ExecutorService中的awaitTermination“发生在之前”任何代码执行后呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助理解ExecutorService#awaitTermination(timeout)行为。

Please, help to understand ExecutorService#awaitTermination(timeout) behaviour.

我在我的代码中观察到情况:

I'm observing situation when I have in my code:

private void shutdownAndAwaitTermination(ExecutorService threadPool){
    threadPool.shutdown(); 
    try {
        if (!threadPool.awaitTermination(threadPoolTimeout, TimeUnit.HOURS)){
            threadPool.shutdownNow(); 
            if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                logger.warn("Pool did not terminate");
            }
        }
    }
    catch (InterruptedException ie)     {
        threadPool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

在此情况下,池中的任务是否完成

Does the tasks in pool complete in this case before any other calls after shutdownAndAwaitTermination() in same thread ?

看看生产中发生了什么,我相信答案是没有,但我只想了解如何确保在调用shutdownAndAwaitTermination()后发生的任何代码会在池中完成最后一个任务后发生。

Looking into what is happening on production, I believe that the answer is no, but I just want to understand how to make sure that any code placed after call to shutdownAndAwaitTermination() will happen after last task in pool completes.

谢谢。

推荐答案

不,任务可以从 shutdownAndAwaitTermination()方法,因为你实际上并不等待终止。如果等待的线程被中断,或者它花了太长时间,你停止等待,即使任务可能仍在运行。

No, tasks could definitely complete after you return from your shutdownAndAwaitTermination() method, because you don't actually await termination. If the waiting thread is interrupted, or if it takes too long, you stop waiting, even though tasks may still be running.

即使你调用 shutdownNow(),你的任务可能不会响应中断c $ c> ExecutorService 不保证使用中断)。因此,任务可能仍在运行。

Even if you call shutdownNow(), your tasks may not respond to interruption (and in general, ExecutorService isn't guaranteed to use interruption). So tasks may still be running.

如果要确保任务完成发生在之前从此方法返回,您必须继续尝试,直到 awaitTermination()返回 true ,尽管中断等。这将是一个糟糕的设计,如果你的任务通过 Future 返回结果,而不是非原子性地产生副作用。这样,可以对成功完成的任务执行操作,而可以忽略未完成的任务。

If you want to ensure task completion happens-before returning from this method, you have to keep trying until awaitTermination() returns true, in spite of interrupts, etc. That would be a bad design, so it would be better if your tasks returned their results via a Future instead of producing side-effects non-atomically. That way, tasks that complete successfully can be acted upon, while tasks that do not complete can be ignored.

这篇关于ExecutorService中的awaitTermination“发生在之前”任何代码执行后呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆