为什么ExecutorService接口未实现AutoCloseable?

编程入门 行业动态 更新时间:2024-10-22 17:35:42
本文介绍了为什么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 … }

推荐答案

该 ExecutorService 实际上有两种与关机有关的方法;基于一个简单的事实,即两种关闭服务的方式都有意义.

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?

本文发布于:2023-11-29 16:43:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   ExecutorService   AutoCloseable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!