Shutdown Hook

Email this to someonePrint this pageShare on Google+2Share on Facebook1Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon0

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


 

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


Same example of Shutdown Hook by annonymous class:


Output:

Email this to someonePrint this pageShare on Google+2Share on Facebook1Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on StumbleUpon0

About Team

Browse Archived Articles by Team

  • Team

    Hi,

    You can connect us at our facebook page Thats Java Info and at our Twitter account @ThatsJavaInfo whenever you feel to contribute with your valuable ideas.
    You can email us at contact@thatsjavainfo.com . For any query/discussion mail us at admin@thatsjavainfo.com .

    Warm Regards,
    Team
    ThatsJavaInfo