tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Runtime > Shutdown Hook

Shutdown Hook 

The JVM exits when System.exit method is invoked or when the last non daemon thread exits. When the virtual machine begins its shutdown sequence it starts the execution of registered shutdown hooks in some unspecified order. The shutdown hooks are useful to perform clean up activities.

File Name  :  
com/bethecoder/tutorials/runtime/ShutdownHookTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.runtime;

public class ShutdownHookTest {

  public static void main(String[] argsthrows Exception {
    
    //Order of execution of hooks is unknown
    for (int i = ; i < ; i ++ ) {
      Runtime.getRuntime().addShutdownHook(getHook("HOOK#"+i));  
    }
    
    System.out.println("Sleeping");
    Thread.sleep(6000);
    System.out.println("About to exit JVM");
    System.exit(0);
  }
  
  public static Thread getHook(final String hookName) {
    
    return new Thread() {      
      public void run() {
        System.out.println("HookName : " + hookName);
      }
    };
  }
  
}
   

It gives the following output,
Sleeping
About to exit JVM
HookName : HOOK#3
HookName : HOOK#5
HookName : HOOK#2
HookName : HOOK#1
HookName : HOOK#0
HookName : HOOK#4



 
  


  
bl  br