Java Shutdown Hook

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Shutdown Hook

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

When does the JVM shut down?

The JVM shuts down when:

  • user presses ctrl+c on the command prompt
  • System.exit(int) method is invoked
  • user logoff
  • User shutdown etc.

The add Shut down Hook (Thread hook) method

The add Shut down Hook () method of Runtime class is used to register the thread with the Virtual Machine. Syntax:

  1. public void add Shut down Hook(Thread hook){}  

The object of Runtime class can be obtained by calling the static factory method get Runtime (). For example:

Runtime r = Runtime.getRuntime ();

Factory method

The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook

  1. class MyThread extends Thread{  
  2.     public void run(){  
  3.         System.out.println("shut down hook task completed..");  
  4.     }  
  5. }  
  6.   
  7. public class TestShutdown1{  
  8. public static void main(String[] args)throws Exception {  
  9.   
  10. Runtime r=Runtime.getRuntime();  
  11. r.addShutdownHook(new MyThread());  
  12.       
  13. System.out.println("Now main sleeping... press ctrl+c to exit");  
  14. try{Thread.sleep(3000);}catch (Exception e) {}  
  15. }  
  16. }  
Output:Now main sleeping... press ctrl+c to exit
       shut down hook task completed..

Note: The shutdown sequence can be stopped by invoking the halt (int) method of Runtime class.

Same example of Shutdown Hook by anonymous class:

  1. public class TestShutdown2{  
  2. public static void main(String[] args)throws Exception {  
  3.   
  4. Runtime r=Runtime.getRuntime();  
  5.   
  6. r.addShutdownHook(new Thread(){  
  7. public void run(){  
  8.     System.out.println("shut down hook task completed..");  
  9.     }  
  10. }  
  11. );  
  12.       
  13. System.out.println("Now main sleeping... press ctrl+c to exit");  
  14. try{Thread.sleep(3000);}catch (Exception e) {}  
  15. }  
  16. }  
Output:Now main sleeping... press ctrl+c to exit
       shut down hook task completed..