为什么ExecutorService接口未实现AutoCloseable? [英] Why does the ExecutorService interface not implement AutoCloseable?

查看:123
本文介绍了为什么ExecutorService接口未实现AutoCloseable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法在线程执行器上调用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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