Monday, June 23, 2008

Detecting the Shutdown of a JVM programmatically


How can you detect the Shutdown of a JVM programmatically?

One possible way of doing it by adding a Shudown Hook to the JVM (Is there any other way?). Of course I'm not considering the case where a new process would be launched just to kill the JVM. It should be normal JVM Shutdown - without interference of an external interrupt by any user process.

OKay... so let's discuss how can we write and add a Shutdown Hook for detecting the Shutdown of the JVM. Read more about Shutdown Hooks in this article - Shutdown Hooks in Java & their uses >>

As we know that a shutdown hook is just another Java Thread registered with the JVM, which is started (and hopefully completes execution) during the JVM Shutdown. Since, the hook(s) may not get enough time to finish their execution, hence it's always a better idea NOT to keep long running code inside a Shutdown Hook. Many Operating Systems allow only a fixed time for the entire JVM process to shut down and in case the Shutdown Hooks don't complete their execution within that time they are forcibly terminated using Runtime.halt() method.

Example: writing and adding a simle Shutdown Hook in Java

...
class CustomShutdownHook extends Thread {
...
public void run(){
...
System.out.println("Shutdown of JVM detected!");
//... do some tasks quickly in response to Shutdown
...
}
...
}

public class CustomShutdownHookDemo {
...
public static void main(String[] args){
...
//... creating a shutdown hook
CustomShutdownHook customShutDownHook = new CustomShutdownHook();
...
//... registering a shutdown hook
Runtime.getRuntime().addShutdownHook(customShutdownHook);
...
}
}

On JVM shutdown the CustomShutdownHook thread will be started and executed and therefore it'll print "Shutdown of JVM detected!" on System.out and execute other statements written in the run() method of the CustomShutdownHook thread.

Why would you need to detect the JVM Shutdown Programmatically?

There may be quite a few reasons including - you may like to clear some cache, realse some previously held important resources, or may be for the simple purpose of logging the time of the Shutdown, closing a log file, etc. But as you know Shutdown Hooks are not guaranteed to run everytime as the JVM process may be terminated abruptly (maybe by the underlying OS due to an error in some native code), hence you should avoid putting some code in a shutdown hook, which may cause the state of your application to become inconsistent in such a case.

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


No comments: