JVM Shutdown Hook

As the name specifies its a Hook provided by JVM to register a Thread when it shut down. i.e. piece of instructions that JVM should execute before going down.

How To Achieve
The

java.lang.Runtime.addShutdownHook(Thread hook)

method registers a new virtual-machine shutdown hook.

When to Use

  • To release critical resources in the event of unexpected JVM shutdown like closing DB Connections. Note : use of finally block to release a resource is completely different.
  • Saving an application state.e.g. when you exits from most of the IDEs, they remember the last view
  • Send a message to System Administrator that application is shutting down.

When JVM Shutdowns (i.e. when shutdown hook will get invoked)

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked
  • The virtual machine is terminated in response to a user interrupt, such as typing CTRL + C, or a system-wide event, such as user logoff or system shutdown.

Example :

package in.bibek;

public class ShutdownHook {
   public static void main(String[] args) {
         Runtime.getRuntime().addShutdownHook(new Message());
         System.out.println("JVM Shutdown Hook Registered.");
         System.out.println("Before System exit.");
         System.exit(0);
         System.out.println("Atfer System.exit.");
   }
}
class Message extends Thread {
    public void run() {
       System.out.println("Shutdown Hook Called.");
    }
 }

Output :
JVM Shutdown Hook Registered.
Before System exit.
Shutdown Hook Called.

Refs:

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.