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 ?
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").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With