Monday, March 12, 2012

Java JVM Shutdown Hook - tutorial

JVM shutdown hooks provide a clean and simple mechanism for registering application-specific behavior that performs the required cleanup work when a JVM terminates.

It is a Java feature that let you have a piece of Java code run whenever the JVM terminates under one of the following conditions:

  - The program exits normally, such as when the last non-daemon thread exits or when the                         Runtime.exit() method is invoked.

  -  The virtual machine is terminated in response to a user interrupt, such as typing CTRL-C, or a                      system-wide event, such as user logoff or system shutdown (for example, the JVM receives               one of  the interrupt signals SIGHUP (Unix Only), SIGINT, or SIGTERM).

A shutdown hook is a Java class that extends java.lang.Thread and is get registered with the Runtime.addShutdownHook()method. Your application may install multiple shutdown hooks. On JVM termination, each shutdown hook will be started and will run concurrently, so the normal rules of thread synchronization apply. You can write shutdown hooks to do anything that a normal thread would do; the JVM will treat them like any other.

Generally we write a shutdown hook to do any last-minute tidying, such as flushing memory buffers, closing files, or displaying an exit message. The JVM will always wait until all shutdown hooks have completed before continuing with the rest of the shutdown sequence, so it is important that your shutdown hooks do actually complete.

The following example shows how to write and install a Java shutdown hook.

/**
 * Implementation of JVM shutdown hook
 *
 * @author abdul
 *
 */
public class ShutDownHook {
    public static void main(String args[]) {
        ShutDownHook hook = new ShutDownHook();
        System.out.println( "Running Main Application..." );
        // Java code to register shutdown hook:
        hook.attachShutDownHook();
        // You can unregister the shutdon hook too.
        hook.removeShutdownHook();
        System.out.println("Exit");
    }

    Thread shutdown =new Thread() {
        @Override
        public void run() {
            //Do your cleaning stuff here eg closing connection,Saving some logs etc
            System.out.println("Inside Add Shutdown Hook");
        }
    };

    private void attachShutDownHook() {
        Runtime.getRuntime().addShutdownHook(shutdown);
        System.out.println("Shut Down Hook Attached.");
    }

    public void removeShutdownHook(){
        Runtime.getRuntime().removeShutdownHook(shutdown);
    }
}

 


There is also a method named removeShutdownHook, which also takes the reference to the Thread object as a parameter. This method allows you to remove a Thread from the list of threads to be started by the VM before it closes (Runtime.getRuntime().removeShutdownHook(shutdown); for the above shutdown hook example).

FAQ On JVM Shutdown Hook API

1 comment:

  1. very useful post. for more info refer this link http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

    ReplyDelete

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...