10

Is it necessary to shutdown an ExecutorService at some point if it runs in a Tomcat container for a Servlet. If yes, then where should I call the shutdown? I tried adding it after the submit() call but when I fire another request to the Servlet from a client browser, I get a RejectedExecutionException which is probably because I did a shutdown? I am trying to understand how it works in a Servlet within Tomcat and how I should use it.

I am doing the following in my webApplication (which seems to work fine without any shutdown):

// In configuration class
@Bean (name = "executorService")
public ExecutorService executorService() {
  return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
}

// In some other class
@Qualifier("executorService")
@Autowired
private ExecutorService executorService;
....
private void load() {
  executorService.submit(new Runnable() {
    @Override
    public void run() {
        doSomethingInTheBackground();
    }
});

// If I enable this I will get a RejectedExecutionException 
// for a next request.
// executorService.shutdown();

}

Diyarbakir
  • 1,999
  • 18
  • 36
  • Related: http://stackoverflow.com/questions/31703865/do-we-need-to-shutdown-executorservice-fixedthreadpool – Marvin Jul 29 '15 at 20:36
  • @Marvin I have read the comments in the link thanks. But where should I Call shutdown because it throws an exception for consecutive requests. And what would happen if I just don't shutdown? – Diyarbakir Jul 29 '15 at 20:52

1 Answers1

8

The idea behind the ExecutorService is to reuse threads. Creating threads is expensive and usually it is more efficient to create a thread once and then use that same thread multiple times. This is exactly what an ExecutorService does: it manages a pool of (possibly idle) threads and assigns work to them when you call its submit methods.

In a typical application you therefore do not want to shutdown the ExecutorService. You should however shut the ExecutorService down properly if your application is terminated. Since you are using Spring you don't have to worry about that:

By default, beans defined using Java config that have a public close or shutdown method are automatically enlisted with a destruction callback. [See the documentation.]

That means, if you close the ApplicationContext, Spring will automatically shutdown the ExecutorService for you.

hzpz
  • 7,536
  • 1
  • 38
  • 44
  • Thank you very much for this explanation. The fact that Spring manages the shutdown was the missing piece I was looking for. – Diyarbakir Jul 30 '15 at 07:25