java – 为什么ExecutorService接口不实现AutoCloseable?

栏目: Java · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/41393417/why-does-the-executorservice-interface-not-implement-autocloseable

没有在线程执行程序上调用shutdown()将导致永远不会终止应用程序.关闭ExecutorService的最佳做法是:

ExecutorService service = null;
try {
  service = Executors.newSingleThreadExecutor();
  // Add tasks to thread executor
  …
} finally {
  if(service != null) service.shutdown();
}

由于 Java 知道try-with-resources概念,如果我们能做到这一点,那不是很好吗?

try (service = Executors.newSingleThreadExecutor())
{
  // Add tasks to thread executor
  …
}
ExecutorService

实际上有两个关机相关的方法;基于简单的事实,即关闭服务的两种方式都是有道理的.

那么你怎么会自动关闭一个服务呢?以一贯的方式为大家工作?

所以,在我眼中的合理解释:你不能使ExecutorService成为一个AutoClosable,因为该服务没有像关闭一样的操作;但是两个!

如果您认为您可以善用这种自动关闭服务,则使用“委托”来编写自己的实施将是5分钟的事情!或者大概10分钟,因为你会创建一个调用shutdown()作为close操作的版本;而另一个则执行shutdownNow().

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/41393417/why-does-the-executorservice-interface-not-implement-autocloseable


以上所述就是小编给大家介绍的《java – 为什么ExecutorService接口不实现AutoCloseable?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python Algorithms

Python Algorithms

Magnus Lie Hetland / Apress / 2010-11-24 / USD 49.99

Python Algorithms explains the Python approach to algorithm analysis and design. Written by Magnus Lie Hetland, author of Beginning Python, this book is sharply focused on classical algorithms, but it......一起来看看 《Python Algorithms》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具