Jacques René Mesrine
Jacques René Mesrine

Reputation: 47875

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 ?

Upvotes: 10

Views: 3390

Answers (3)

Toby
Toby

Reputation: 9803

I agree with Steve, resetting the interrupt flag gives code outside your control a chance to react to the event.

tempus-fugit offers a convieance method to do this for you, along with an explict timeout exception if things take too long.

waitOrTimeout(shutdown(executor), timeout);

Have a look under the concurrency section of the docs if its of interest... tempusfugitlibrary.org/documentation

This example demonstrates its usage, both for awaiting completion and more aggressive shutdown.

Upvotes: 0

Steve McLeod
Steve McLeod

Reputation: 52478

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.

Upvotes: 1

skaffman
skaffman

Reputation: 403591

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

Upvotes: 5

Related Questions