Shutdown Hook In Java Example
Chapter:
Exception Handling
Last Updated:
03-08-2016 18:55:48 UTC
Program:
/* ............... START ............... */
public class JavaShutdownHook {
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 a = 1000 / 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");
}
}
}
/* ............... END ............... */
Output
Inside try
Inside catch
Shutdown Hook is running
Notes:
-
A java program can attach a shutdown hook to JVM. A shutdown hook is a piece of code that JVM tries to run before exiting.
Tags
Shutdown Hook, Exception, Java