Tuesday, June 24, 2008

Shutting Down Java Apps [Howto]

In most cases, users do not always follow the recommended procedure to exit their java applications. They may not type "quit" or "exit" and may instead hit Ctrl+C to terminate the process immediately. In these cases, the application does not get a chance to clean-up.

Fortunately, there is a way to ask the JVM to execute some clean-up code before exiting. This is done by using ShutdownHooks which are registered with System Runtime. The JVM starts all registered shutdown hooks concurrently when shutting down.

Here are the steps involved when creating shutdown hooks:

1. Create the shutdown hook class:

public class AppShutdownHook extends Thread{
    public void run(){
        logger.info("Running shutdown hook...") ;
        //cleanup e.g. close database connections
    }
}
2. Register the shutdown hook:
public class App{
    public App(){
        Runtime.getRuntime().
          addShutdownHook(new AppShutdownHook()) ;
    }
}
Note that no guarantee can be made about whether or not any shutdown hooks will be run if the JVM aborts with the SIGKILL signal (kill -9) on Unix or the TerminateProcess call on MS Windows.

However, SIGTERM (kill with no arguments) will work.

Reference:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

1 comment:

  1. Really very good blog for wow gold its really excellent. The content of your
    blog Is really superb.

    ReplyDelete

Note: Only a member of this blog may post a comment.