JVM Shutdown Hook

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

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 :

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.