Search code examples
javaspringexecutorserviceshutdown

Is spring taking care of shutting down your ExecutorService?


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.


Solution

  • Yes Spring does that for you, but it will destroy the beans only when the container is shutting down, you might want to shutdown the executory service once it has processed all the tasks. You can create ExecutorService bean as prototype but since spring will not completely manage its lifecycle you'll have to call its destroy method yourself once your task is done.