java - spring 是否负责关闭您的 ExecutorService?

标签 java spring executorservice shutdown

在我的配置类中,我有一个用于固定线程池的 bean

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

我稍后会在某堂课上 Autowiring 它。在我研究的过程中,我发现这是关闭执行程序服务的最佳方法,如 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的类中,我将来可能会在其他一些类中使用这个bean,这似乎是错误的。

最佳答案

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

关于java - spring 是否负责关闭您的 ExecutorService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940536/

相关文章:

javac -Xlint :overrides not working

java - 如何在注释中使用 Spring 变量?

java - Spring Rest - 发布多个文件

spring - 具有 Spring Data 和 Spring JPA 的 Atomikos - 持久性问题

java - 执行器服务和scheduleWithFixedDelay()

java - 在用户输入java上暂停线程池

java - 在所有提交的任务无阻塞地完成后关闭 Java Executor

java - MongoDB 使用 Spring Data Mongo 在集合中自动递增 Integer Id

java - 让 OnLongClick 在 ListView Android Studio 中工作

android - Windows 8 - 运行 Eclipse(未找到 Java VM)