Is spring taking care of shutting down your ExecutorService?

时间:2018-06-20 05:04:13

标签: java spring executorservice shutdown

In my config class I have a bean for FixedThreadPool

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

and I autowire it later in some class. As I was researching, I came across that this was the best way to do a shutdown of an executor service, as per 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();
   }
 }

But I also found that spring does that for you, if your ExecutorService is a bean. My question is - is this true? If it is, it's certainly easier, since I am in doubt of where to put the code mention above. If I put it in the class where I am using this bean, I might use this bean in some other classes in the future, and it just seems wrong.

1 个答案:

答案 0 :(得分:1)

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