views:

29

answers:

1

In my application, I use ExecutorService a lot for making async calls.

ExecutorService executorService = Executors.newFixedThreadPool(10);

And I shutdown the executorService only when the app (web based) shuts down. Recently when debugging some issues I was looking through this code and wondering whether there can be cases during the execution of the program when I am forced to shutdown the ExecutorService and restart it i.e. new set of pooled threads. So I wanted to know what typical scenarios/unexpected application behavior can force me to do so?

The typical exceptions that I check for are ExecutionException, InterruptedException, CancellationException but I don't do much apart from logging them.

+1  A: 

The general answer is that you shouldn't have to recycle the pool; it's designed to minimize your need to do that. The two cases you might consider are:

  • An abrupt unhandled exception in one of your tasks. In this case, the task will fail (and you have the option of catching unhandled exceptions via the thread pool hooks, or a UncaughtExceptionHandler) and the worker thread may exit. However, the thread pool handles this cleanly, and the next request into the thread pool will create a replacement if need be.

  • A worker thread deadlocks. This one is not so easy to predict or detect -- I can't imagine structuring an application around recycling a thread pool to cope with deadlocked worker threads.

Apart from these two edge conditions, I see no reason to worry about periodic cycling to a new thread pool.

Some folks do create and destroy thread pools because they aren't aware of the CompletionService, convenience methods like invokeAll(), and the flexibility of monitoring completion with Futures.

andersoj