Graceful shutdown of threads and executor

A typical orderly shutdown of an ExecutorService might look something like this:

final ExecutorService executor;

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        executor.shutdown();
        if (!executor.awaitTermination(SHUTDOWN_TIME)) { //optional *
            Logger.log("Executor did not terminate in the specified time."); //optional *
            List<Runnable> droppedTasks = executor.shutdownNow(); //optional **
            Logger.log("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed."); //optional **
        }
    }
});

*You can log that the executor still had tasks to process after waiting the time you were willing to wait.
**You can attempt to force the executor’s worker Threads to abandon their current tasks and ensure they don’t start any of the remaining ones.

Note that the solution above will work when a user issues an interrupt to your java process or when your ExecutorService only contains daemon threads. If, instead, the ExecutorService contains non-daemon threads that haven’t completed, the JVM won’t try to shutdown, and therefore the shutdown hooks won’t be invoked.

If attempting to shutdown a process as part of a discrete application lifecycle (not a service) then shutdown code should not be placed inside a shutdown hook but at the appropriate location where the program is designed to terminate.

Leave a Comment