java - 在库中管理 ExecutorService 的最佳实践是什么?

标签 java threadpool shutdown-hook

在我的一个库中,我使用具有 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.

  1. All tasks, when executed from the ManagedExecutorService, will run with the Java EE component identity of the component that submitted the task.
  2. 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
  3. 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:

  1. All attempts to submit new tasks are rejected.
  2. All submitted tasks are cancelled if not running.
  3. All running task threads are interrupted.
  4. All registered ManagedTaskListeners are invoked

关于java - 在库中管理 ExecutorService 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125662/

相关文章:

java - 如何确保在退出 Java 应用程序之前运行一段代码

java - 关闭钩子(Hook)可以用于稍长的任务吗

java - 有什么方法可以以编程方式关闭 Java 进程但不调用 JVM 关闭 Hook ?

java - 是否有用于处理构建 URL 的 Java 包?

java - 减少 Wildfly 连接超时

java - 如何判断一个组件是否可见?

c# - 为什么我对 Runspace.Open() 的调用没有返回?

python - 确定工作线程是否正在执行任何工作

java - 如何根据 jSpinner 中超出最小/最大范围的文本字段的无效手动编辑来触发事件

java - 为java threadPool中的每个线程设置超时