Wednesday, 29 July 2015

In Detail: JVM ShutDown Hook


Suppose if you want to run some piece of code when the JVM is shutting down, you can do it using addShutdownHook() method of Runtime class.

Some cases where you want to use this method are,

1. Saving the application state i.e Most IDEs such as Eclipse saves state at the time of exit to remember the user settings.
2. Closing some database connections.
3. Sending a message to System administrator that the application is going down. 

 Runtime.addShutdownHook(Thread hook) :

Runtime.addShutdownHook() method registers a new virtual-machine shutdown hook to the JVM. This thread hook runs at the time of JVM shutdown only.

What Causes JVM to Shutdown:

1. JVM shuts down when all the non-daemon threads have finished execution.
2. Call to System.exit() method.
3. When the user types CTRL+C.
4. When user logoff or Machine shutdown.

What is shutdown hook?

As you can see in the method signature i.e Runtime.addShutdownHook(Thread hook), it is just a Thread instance. So you need to add all your code in the thread's run method. This method registers the given thread with JVM, so that at the time of JVM shutdown, it runs all registered hooks concurrently. JVM doesn't follow any order while starting these threads.

Once all the hooks finished, JVM will halt.

Sample Code :
package com.speakingcs.runtime;

public class JVMShutdownHook {

 public static void main(String[] args) {
  
  JVMShutdownHook jvmSdh = new JVMShutdownHook();
  
  jvmSdh.attachShutDownHook();
  
  // add some sample code, jvm runs shutdown hook after this
  for(int i = 0;i < 10; i++) {
   System.out.print(i+" ");
  }
  System.out.println();
 }

 private void attachShutDownHook() {
  
  System.out.println("Registering shutdown hook");
  
  Runtime.getRuntime().addShutdownHook(
    
   new Thread() {
    public void run() {
     System.out.println("running shutdown hook code");
     System.out.println("finished code execution");
    }
   }
  );
  System.out.println("Shutdown hook registered");
 }
}

output is:
Note:

1. Don't call Runtime.getRuntime().halt() to shutdown JVM, as this will not invoke any shutdown hooks attached. It forcefully shutdowns all running processes.
2. You can attach any number of shutdown hooks you required, there is no limitation on that.
3. Always attach shutdown hook before JVM starts shutting down, otherwise, It throws IllegalStateException with message, Shutdown in progress.
4. Don't attach same hook again, if you do, it will throw IllegalArgumentException with message "Hook previously registered".

How to De-Register a Hook:

Calling removeShutdownHook(hook) method de-registers a previously registered virtual-machine shutdown hook. It returns true if the specified hook had previously been registered and was successfully de-registered, false otherwise.

It throws IllegalStateException, if the call happened after JVM started shutting down.

Avoid Thread Related Issues with Hooks:

As a shutdown hook is nothing but a thread and one can attach more than one shutdown hook, all thread related issues such as deadlocks and race conditions can happen, so you need to take particular attention to avoid these issues.

Avoid Long Running Hooks: 

The shutdown hooks should finish their work quickly because when the virtual machine is terminated due to user logoff or system shutdown, the underlying operating system may only allow a fixed amount of time to the process to shutdown and exit.

Cases when shutdown hook doesn't run as expected:

In some rare cases, the JVM aborts without running all the shutdown hooks. This happens, when you terminate the JVM from task manager in windows, and by other ways in other Operating systems. Therefore in all cases when the JVM shutdowns abnormally, the hooks may not run.

Exception Handling by JVM:
 
In case if your shutdown hook throws any exception, JVM applies standard exception propagation mechanism and for uncaught exceptions, the default uncaught exception handlers will be invoked.

Conclusion:

You can use JVM shutdow Hook to plugin some arbitrary code into the shutdown sequence of JVM. One should be careful with the consequences and implications of the actions done by Shutdown Hook before writing one. 

0 comments:

Post a Comment

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