如何 stop/terminate/resume 托管执行器服务

How to stop/terminate/resume Managed Executor Service

我正在使用 Managed Executor Service 来实现处理后台任务的服务。应该允许该服务停止 运行 任务并终止工作线程,并将其 return 放入线程池以供下一个任务使用。停止后,您可以从中断的地方继续吗?

不,无法在 Java EE 环境中关闭、终止或恢复 ManagedExecutorService。

根据 Java EE Concurrency Utilities 1.0 规范,项目符号 #2

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().
  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.

这似乎是一个限制,但之所以有此限制,是因为 ManagedExeuctorService 由 Java EE 产品提供商为您管理。
所以不用担心在 Java EE 中启动、停止或恢复 ManagedExeuctorService。

现在,如果您想等到所有任务都完成,这是一个完全合理的要求。这可以通过多种方式实现:

提交任务后,您将需要以您选择的任何方式管理 Future<T> 的集合,并使用 get()(阻塞)或 isDone()(非阻塞) ) 检查它们是否完成。