问题描述
无法在线程执行器上调用shutdown()
将导致应用程序永不终止.
Failing to call shutdown()
on a thread executor will result in a never terminating application.
关闭ExecutorService的最佳实践是:
Best practice to shut down the ExecutorService is this:
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
// add tasks to thread executor
…
} finally {
if (service != null) service.shutdown();
}
由于Java知道try-with-resources概念,如果我们能做到这一点岂不是很好吗?
Since Java knows the try-with-resources concept, wouldn't it be nice if we could do this?
try (service = Executors.newSingleThreadExecutor())
{
// add tasks to thread executor
…
}
推荐答案
该实际上有两种与关机有关的方法;基于一个简单的事实,即两种关闭服务的方式都有意义.
That ExecutorService has actually two shutdown-related methods; based on the simple fact that both ways of shutting down a service make sense.
因此:您将如何自动关闭服务?以一致的方式为每个人工作?!
Thus: how would you auto-close a service then? In a consistent manner that works for everybody?!
因此,在我眼中,合理的解释是:您不能将ExecutorService设为AutoClosable,因为该服务没有像操作这样的关闭"操作;但是两个!
So, the reasonable explanation in my eyes: you can't make an ExecutorService a AutoClosable because that service does not have a single "close" like operation; but two!
如果您认为可以充分利用这种自动关闭服务,那么使用委托"编写自己的实现将是5分钟的事情!大概是10分钟,因为您将创建一个调用shutdown()
的版本作为关闭操作.还有一个代替shutdownNow()
的人.
And if you think you could make good use of such an auto-closing service, writing up your own implementation using "delegation" would be a 5 minute thing! Or probably 10 minutes, because you would create one version calling shutdown()
as close operation; and one that does shutdownNow()
instead.
这篇关于为什么ExecutorService接口未实现AutoCloseable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!