Javatpoint Logo
Javatpoint Logo

Java Shutdown Hook

A special construct that facilitates the developers to add some code that has to be run when the Java Virtual Machine (JVM) is shutting down is known as the Java shutdown hook. The Java shutdown hook comes in very handy in the cases where one needs to perform some special cleanup work when the JVM is shutting down. Note that handling an operation such as invoking a special method before the JVM terminates does not work using a general construct when the JVM is shutting down due to some external factors. For example, whenever a kill request is generated by the operating system or due to resource is not allocated because of the lack of free memory, then in such a case, it is not possible to invoke the procedure. The shutdown hook solves this problem comfortably by providing an arbitrary block of code.

Taking at a surface level, learning about the shutdown hook is straightforward. All one has to do is to derive a class using the java.lang.Thread class, and then provide the code for the task one wants to do in the run() method when the JVM is going to shut down. For registering the instance of the derived class as the shutdown hook, one has to invoke the method Runtime.getRuntime().addShutdownHook(Thread), whereas for removing the already registered shutdown hook, one has to invoke the removeShutdownHook(Thread) method.

In nutshell, the shutdown hook can be used to perform cleanup resources or save the state when JVM shuts down normally or abruptly. Performing clean resources means closing log files, sending some alerts, or something else. So if you want to execute some code before JVM shuts down, use the 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(Thread hook) method

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

Syntax:

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

The removeShutdownHook(Thread hook) method

The removeShutdownHook() method of the Runtime class is invoked to remove the registration of the already registered shutdown hooks.

Syntax:

True value is returned by the method, when the method successfully de-register the registered hooks; otherwise returns false.

Factory method

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

Simple example of Shutdown Hook

FileName: MyThread.java

Output:

Now main sleeping... press ctrl+c to exit
shut down hook task completed.

Same example of Shutdown Hook by anonymous class:

FileName: TestShutdown2.java

Output:

Now main sleeping... press ctrl+c to exit
shut down hook task completed.

Removing the registered shutdown hook example

The following example shows how one can use the removeShutdownHook() method to remove the registered shutdown hook.

FileName: RemoveHookExample.java

Output:

The program is beginning ...
Waiting for 2 seconds ...
The program is terminating ...

Points to Remember

There are some important points to keep in mind while working with the shutdown hook.

No guarantee for the execution of the shutdown hooks: The first and the most important thing to keep in mind is that there is no certainty about the execution of the shutdown hook. In some scenarios, the shutdown hooks will not execute at all. For example, if the JVM gets crashed due to some internal error, then there is no scope for the shutdown hooks. When the operating system gives the SYSKILL signal, then also it is not possible for the shutdown hooks to come into picture.

Note that when the application is terminated normally the shutdown hooks are called (all threads of the application is finished or terminated). Also, when the operating system is shut down or the user presses the ctrl + c the shutdown hooks are invoked.

Before completion, the shutdown hooks can be stopped forcefully: It is a special case of the above discussed point. Whenever a shutdown hooks start to execute, one can forcefully terminate it by shutting down the system. In this case, the operating system for a specific amount of time. If the job is not done in that frame of time, then the system has no other choice than to forcefully terminate the running hooks.

There can be more than one shutdown hooks, but there execution order is not guaranteed: The JVM can execute the shutdown hooks in any arbitrary order. Even concurrent execution of the shutdown hooks are also possible.

Within shutdown hooks, it is not allowed to unregister or register the shutdown hooks: When the JVM initiates the shutdown sequence, one can not remove or add more any existing shutdown hooks. If one tries to do so, the IllegalStateException is thrown by the JVM.

The Runtime.halt() can stop the shutdown sequence that has been started: Only the Runtime.halt(), which terminates the JVM forcefully, can stop the started shutdown sequence, which also means that invoking the System.exit() method will not work within a shutdown hook.

Security permissions are required when using shutdown hooks: If one is using the Java Security Managers, then the Java code that is responsible for removing or adding the shutdown hooks need to get the shutdown hooks permission at the runtime. If one invokes the method without getting the permission in the secure environment, then it will raise the SecurityException.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA