Catching JVM Shutdown event
public class ShutDownHookTest {Compile and run this sample code and press Crt+C to exit the application, you can see that "System is Shutting Down" message prints before application exiting.
public static void main(String [] args) throws Exception {
System.out.println("System Started...");
Runtime.getRuntime().addShutdownHook(new Thread( new Runnable() {
public void run() {
System.out.println("System is Shutting Down...");
}
}));
Thread.sleep(10000);
}
}
But we have to be careful when using this, because if the shutdown code we attach to the shutdown hook end up in an infinite loop, our application will be stuck and only way to exit will be killing the process.