Wednesday, June 15, 2011

JVM shutdown hook (Surviving abrupt shotdown)

Project I am working currently requires the ability to detect shutdown on JVM. Its basically required to be detected so that active connections to the JMS server to be destroyed. I wrote code to destroy connection on ServletContextListener which worked fine for some scenario, but failed if I kill web server processes explicitly.


The solution is a little known feature of the language that lets you register JVM shut down hooks. A shut down hook is simply a Thread that is registered with the JVM and run just before the JVM shuts down.

Here is code snippet to register shutdown hook with JVM:

Runtime.getRuntime().addShutdownHook(new Thread()
  {
   public void run()
   {
    // your code here which needs be executed before shutdown
   }
  });

Runtime.getRuntime().addShutdownHook(new Thread()
  {
   public void run()
   {
    try
    {
     Thread.sleep(10000);
    }
    catch (InterruptedException ex)
    {
    }
    // halt will bail out without calling further shutdown hooks or
    // finalizers

    Runtime.getRuntime().halt(1);
   }
  });


No comments: