Monday, February 23, 2009

Executing the code while JVM shuts down

A number of times we have encountered a situation where we want a particular piece of code to be executed when our application is exiting. More necessarily we need such a mechanism when we have developed a server and want the code to be executed for any System.exit(0) call or a CTRL + C key combination on the console. A shutdown hook is the way out for this problem. Writing it is very simple. All the code we need to be executed should be written in a Thread and its object should be registered with the Runtime of the JVM. The code is as below.
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        System.out.println("Executing the code while closing down.");
    }
});
A detailed explanation of the above method is provided in the Javadocs for the Runtime class.