Today I was going through articles on gracefully shutting down your Java process and came across the concept of Shutdown hooks in Java. You can register a shutdown hook which is a in-fact a thread and it will run before your JVM is shutdown and your program is terminated.
You can register a shutdown hook thread to your java process with just one line
Runtime.getRuntime().addShutdownHook(yourThreadInstance));
Let us see a demo example
and the output is
Shutdown hook registered
Before calling exit
Inside Shutdown hook
Shutdown hook thread sleeping for 2 seconds
Shutdown hook thread waking up
Shutdown hook thread terminating
You can register a shutdown hook thread to your java process with just one line
Runtime.getRuntime().addShutdownHook(yourThreadInstance));
Let us see a demo example
public class ShutdownHookDemo { public static void main(String args[]){ Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownHook())); System.out.println("Shutdown hook registered"); System.out.println("Before calling exit"); System.exit(0); System.out.println("After exit"); } } class ShutDownHook implements Runnable{ public void run() { System.out.println("Inside Shutdown hook"); System.out.println("Shutdown hook thread sleeping for 2 seconds"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Shutdown hook thread waking up"); System.out.println("Shutdown hook thread terminating"); } }
and the output is
Shutdown hook registered
Before calling exit
Inside Shutdown hook
Shutdown hook thread sleeping for 2 seconds
Shutdown hook thread waking up
Shutdown hook thread terminating
When will Shutdown hook not be initiated
- you cannot register a shutdown hook after shutdown has been initiated. That means you cannot register a shutdown hook from a thread that is itself registered as a shutdown hook.
- Shutdown hook will not be called if Runtime.getRuntime().halt(status); is called. It abruptly shuts down the JVM.
Why above example did not print the statement after System.exit() call?
Code below System.exit() is not reachable though compiler doesn't really know it. Either an exception will be thrown or the JVM will be shutdown. The call never really "returns". So nothing after the exit() call is executed.
Note : You can register multiple shutdown hook threads with the java process. All of them will get executed in parallel once JVM shutdown is initiated.