spring 是否负责关闭您的 ExecutorService?

Is spring taking care of shutting down your ExecutorService?

在我的配置中 class 我有一个用于 FixedThreadPool 的 bean

@Bean
public ExecutorService fixedThreadPool() {
    return Executors.newFixedThreadPool(200);
}

我稍后在 class 中自动装配它。在研究过程中,我发现这是关闭执行程序服务的最佳方式,根据 java docs

   void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

但是我也发现spring does that for you,如果你的ExecutorService是一个bean。我的问题是 - 这是真的吗?如果是这样,那肯定更容易,因为我不确定将上面提到的代码放在哪里。如果我把它放在我正在使用这个 bean 的 class 中,我将来可能会在其他一些 classes 中使用这个 bean,这似乎是错误的。

是的 Spring 会为您做到这一点,但它只会在容器关闭时销毁 bean,您可能希望在处理完所有任务后关闭执行服务。您可以创建 ExecutorService bean 作为原型,但由于 spring 不会完全管理其生命周期,您必须在任务完成后自行调用其 destroy 方法。