Java shutdown hooks
Java allows you to add shutdown hooks to your code. A shutdown hook is simply a thread that has been left in the initialized state. When your JVM is about to shutdown, the shutdown hook thread kicks in. The finalization processes of java objects run after the shutdown hooks complete. The JVM allows you to register more than one shutdown hook.
Let us take a look at how this is done
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class Task { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); Thread thread = new Thread(new ShutDownListener()); runtime.addShutdownHook(thread); someProcess(); } private static void someProcess() { try { System.out.println("I am busy"); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } class ShutDownListener implements Runnable { @Override public void run() { System.out.println("I am shutting down"); } } |
The Task class is a simple class that runs a process. Once this process finishes up, we want the JVM to run a shutdown hook to notify us that the JVM is shutting down. When this program is run, the output is
1 2 | I am busy I am shutting down |
Nice !
Lets experiment a little more. How robust is a shutdown hook ? After the someProcess() method is called let us analyze what will happen when one of the following statements are added