在我的一个库中,我使用具有 5 个线程的固定线程池执行器;我的线程不是重量级的,我的 .get()
有超时,但是对于 ExecutorService
,我创建了它,之后,这是“生死攸关”。
当你完成它时,你应该.shutdown{,Now}()
它;但这是一个库,我无法提前知道它将如何使用:在一个由 servlet 容器等管理的 Web 应用程序中使用一个简单的 main()
。
这感觉不对。我怎样才能做得更好?我应该使用 ExecutorService
之外的其他东西吗?
编辑链接到唯一用户:here ;守护线程可能是一个解决方案,现在我不知道它们是否有我应该注意的缺点......
最佳答案
好吧,这并不是一个真正的答案,更像是一个想法......
正如我在之前的评论中已经提到的,您的 LoadingMessageSourceProvider
组件维护状态,因此必须有人负责正确关闭该组件。您可以尝试通过注册 shutdown hook 将其作为组件的一部分来实现(我不会在这里考虑finalize
:-)。
我宁愿将其留给组件的用户(应用程序),因为它更知道何时关闭。事实上,您正在实现一个具有生命周期的轻量级容器 - 在某种程度上类似于实现 JSR-236 的 Java EE 7 容器提供程序。 .
鉴于您没有可用的 JSR-236 容器,您必须允许调用者管理生命周期。我可以想到一种工厂方法,简化的示例:
// maintains the executor service (one service per factory)
private MessageSourceProviderFactory f = MessageSourceProviderFactory.instance();
private void stuff() {
MessageSourceProvider msp = f.newBuilder()/*. [...] */.build();
// work with the provider
}
// at some point in time the caller decides to finish
private void end() {
f.shutdown(); // shutdown the factory and the ExecutorService
}
JSR-236 第 3.1.6.1 节在生命周期方面相当有趣:
3.1.6.1 Java EE Product Provider Requirements This subsection describes additional requirements for ManagedExecutorService providers.
- All tasks, when executed from the ManagedExecutorService, will run with the Java EE component identity of the component that submitted the task.
- The lifecycle of a ManagedExecutorService is managed by an application server. All lifecycle operations on the ManagedExecutorService interface will throw a java.lang.IllegalStateException exception. This includes the following methods that are defined in the java.util.concurrent.ExecutorService interface: awaitTermination(), isShutdown(), isTerminated(), shutdown(), and shutdownNow().Final Release 3-11
- No task submitted to an executor can run if task’s component is not started.
When a ManagedExecutorService instance is being shutdown by the Java EE Product Provider:
- All attempts to submit new tasks are rejected.
- All submitted tasks are cancelled if not running.
- All running task threads are interrupted.
- All registered ManagedTaskListeners are invoked
关于java - 在库中管理 ExecutorService 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125662/