Java addShutdownHook()
Sometimes we need to execute some code before shutting down the JVM. In java we can attach Java Shutdown Hook to execute some piece of code before going down. If we need to execute some piece of code before JVM shuts down, shutdown hook is used.
Contents
Java addShutdownHook() :
There are verity of reasons which shuts down the application, These reasons are listed below -
- Calling System.exit()
- Pressing Cntrl + C
- System shutdown
- System User Log off
- Completion of thread executions
Example #1 : Shutdown Hook
A shutdown hook is simply an initialized but non started thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
package com.c4learn.thread; class ShutDownThread extends Thread { public void run() { System.out.println("Just before going down.."); } } public class ShutDownExample { public static void main(String[] args) throws InterruptedException { Runtime r1 = Runtime.getRuntime(); r1.addShutdownHook(new ShutDownThread()); System.out.println("Application going down..."); Thread.sleep(3000); } }
Output :
Application going down... Just before going down..
Explanation :
We need to create object of runtime class using the getRuntime() method. getRuntime() method returns the runtime object associated with the current Java application.
Runtime r1 = Runtime.getRuntime();
Now we can attach ShutDownThread to the shutdown hook using following line of code.
r1.addShutdownHook(new ShutDownThread());
Example #2 : Shutdown Hook
package com.c4learn.thread; public class AddShutdownHookDemo { public void attachShutDownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Inside Shutdown Hook"); } }); System.out.println("Hook attached.."); } public static void main(String[] args) { AddShutdownHookDemo sh = new AddShutdownHookDemo(); sh.attachShutDownHook(); System.out.println("Last Program Line.."); System.exit(0); } }
Output :
Hook attached.. Last Program Line.. Inside Shutdown Hook