Thursday, 27 August 2015

Shutdown Hooks


It is one of the concurrency concept.JVM(Java Virtual Machine) can shutdown in an orderly or abruptly manner. An orderly shutdown is nothing but when all normal threads terminates successfully,or by calling System.exit(),or by closing it from special keys like Ctrl+C.
JVM can also be shutdown abrubtly by killing the JVM process or by some OS related issues.

What is Shutdown Hooks ?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().
JVM does not give any guarantee on the order in which shutdown hooks are started.In orderly shutdown JVM starts all registered shutdown hooks.

When all shutdown hooks have completed their task,JVM may choose to run finalizers if runFinalizersOnExit is true.JVM does not stop any of the application thread that are still running at shutdown time.they automatically terminated when JVM halts.Also JVM allows to run application threads concurrently with shutdown hooks.In an abrupt shutdown,shutdown hooks will not run.


Example of Shutdown Hook:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class TestShutdownHook {  
      // shutdown hook thread can be used to perform cleaning of resources.  
      private static class ShutDownHook extends Thread {  
           public void run() {  
                System.out.println("shutdown hook thread started");  
           }  
      }  
      public static void main(String[] args) {  
           ShutDownHook jvmShutdownHook = new ShutDownHook();  
           Runtime.getRuntime().addShutdownHook(jvmShutdownHook);  
           System.out.println("Register Shutdown Hook");  
           System.out.println("calling System.exit() to close the program");  
           System.exit(0);  
           System.out.println("Program Finished");  
      }  
 }  

Output:-  
 Register Shutdown Hook  
 calling System.exit() to close the program  
 shutdown hook thread started  

Advantage of Shutdown Hooks:-

It can be used for service or application cleanup,such as deleting unwanted file, releasing resources like db related resources,file operation resources etc.

 Note:-Shutdown hooks must be thread safe and they should use synchronization when   
 accessing shared data.They should not assume the state of the application(such as all worker   
 thread have completed) at any point of time.They should complete their task as quickly as   
 possible because their existence delays the JVM termination at a time when user may be   
 expecting the JVM to shutdown quickly.  




1 comment:

  1. Thanks for the info, it's a great and simple explanation of Shutdown Hooks.

    ReplyDelete