fastread homefastrread library fastread menu

Java : Shutdown Hook

Tutorial by:Arena Buocel      Date: 2016-05-04 05:25:05

❰ Previous Next ❱

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 addShutdownHook(Runnable r) method

The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine. Syntax:

 
  1. public void addShutdownHook(Runnable r){}  

 

The object of Runtime class can be obtained by calling the static factory method getRuntime(). 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 annonymous 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 Runnable(){  
  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..
       
 

❰ Previous Next ❱


Java

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website