Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know whether a shutdown is currently in progress?

In Tomcat, when the server is being shut down, it tries to set all static variables in classes it knows of to null. By touching these classes, their static initializers are run, which can result in an endless loop for some of our legacy classes which have massive static initializers .

Is there an elegant way to detect whether a shutdown is currently in progress? We could then check at the top of the static initializers whether we are in shutdown mode and then ignore the initialization.

The only way we found which seems to work is anything but elegant:

    try{
       Thread hook = new Thread();
       Runtime.getRuntime().addShutdownHook( hook ); // fires "java.lang.IllegalStateException: Shutdown in progress" if currently in shutdown
       Runtime.getRuntime().removeShutdownHook( hook );
    }catch(Throwable th){
       throw new Error("Init in shutdown thread", th );
    }
like image 379
Epaga Avatar asked Apr 27 '11 14:04

Epaga


2 Answers

You can look if Tomcat uses a new Thread to do shutdown work, if yes you could traverse current threads and look for this thread.

Next, setting up ServletContextListener, so that it turns flag on and off in contextInitialized and contextDestroyed, your classes check that flag.

like image 98
Tomasz Stanczak Avatar answered Oct 15 '22 06:10

Tomasz Stanczak


Do you have control over the webapp configuration? If so, you can disable clearing static references by setting,

clearReferencesStatic=false

in /META-INF/context.xml as stated in the documentation

Otherwise, I agree that setting a flag in the ServletContextListener is probably your best option.

like image 30
John McCarthy Avatar answered Oct 15 '22 06:10

John McCarthy