javacodex.com
Java Examples
Java Examples
memu home questions

Shutdown Hook

A java program can attach a shutdown hook to JVM. A shut downhook is a piece of code that JVM trys to run before exiting.

Source: (ShutDownHook.java)

public class ShutDownHook {
 
   public static void main(String[] args) {
 
      // try and run before shutdown
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            System.out.println("Shutdown Hook is running....");
         }
      });
 
      try {
        System.out.println("Inside try");
 
        // throw  an exception
        int x = 10 / 0;
 
      } catch (Exception e) {
        System.out.println("Inside catch");
        // Shut down and test hook
        System.exit(0);
 
      } finally {
        // should not run
        System.out.println("Inside finally");
      }
   }
}
 

Output:

$ java ShutDownHook 
Inside try
Inside catch
Shutdown Hook is running....

Contact: javacodex@yahoo.com