Friday, March 23, 2012

How to shutdown an ExecutorService

The new executor framework in Java 6 makes it dead easy to create components running in a background thread. Just create an executor, give it a java.util.Runnable and that's it. But how do you do a proper shutdown of a ExecutorService?

1. pExecutorService.shutdown();

2. try {

3.   if (!pExecutorService.awaitTermination(pTimeout, TimeUnit.SECONDS)) {

4.     pExecutorService.shutdownNow();

5.   }

6.   catch (final InterruptedException pCaught) {

7.     pExecutorService.shutdownNow();

8.    Thread.currentThread().interrupt();

9.    }

10. }

First we invoke the shutdown method on the executor service. After this point, no new runnables will be started.
The next step is to wait for already running tasks to complete. In this example we will allow the running tasks to complete within pTimeout seconds. If they don't complete within the given amount of seconds, we invoke shutdownNow(). This method will invoke interrupt on all still running threads.

As a good practice we also make sure to catch  InterrruptedException's and shutdown everything immediately.

2 comments:

  1. Thanks for helpful tutorial. Can you explain why we need: Thread.currentThread().interrupt();

    ReplyDelete
    Replies
    1. you can check out the reason here: http://www.javamex.com/tutorials/threads/thread_interruption_2.shtml#InterruptedException

      Delete