javamultithreadingservletsexception

Shutting down an ExecutorService


In Tomcat, I wrote a ServletContextListener which will start an ExecutorService during startup and terminate it when it is unloaded.

I am following the example in the javadoc for ExecutorService

public void contextDestroyed( ServletContextEvent sce )
{
    executor.shutdown();
    try
    {
        executor.awaitTermination( 50, TimeUnit.SECONDS );
    }
    catch( InterruptedException ie )
    {
        Thread.currentThread().interrupt();
    }
}

My question is should I propagate the InterruptedException in the contextDestroyed() method ?


Solution

  • I would say no. The contextDestroyed method is called by the container as a notification that the context is about to be torn down, it's not asking your permission. Also, the Javadoc does not define what happens if you throw an exception from it, so the results might be unpredictable and/or non-portable.

    What I would do is call executor.shutdownNow() inside the catch block to forcibly terminate the executor (i.e. "you had your chance, now stop").