Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 284
Jacques René Mesrine Avatar asked Sep 16 '09 07:09

Jacques René Mesrine


2 Answers

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").

like image 118
skaffman Avatar answered Oct 19 '22 23:10

skaffman


What you have in your code sample (re-interrupt the current thread) is exactly what I would recommend. Something in Tomcat outside your own code sent the original interrupt, so let Tomcat have a chance to handle it.

I don't know what Tomcat will do with the InterruptedException. It's undefined. But Tomcat initiated the interrupt and Tomcat owns the thread that the contextDestroyed(...) method is running in. The general principle from "Java Concurrency in Practice" that applies here is: the creator of the thread is responsible for handling thread life-cylce issues.

Handling a interrupt is definitely a life-cycle issue.

like image 28
Steve McLeod Avatar answered Oct 19 '22 23:10

Steve McLeod