JVM Shutdown Hook in Java
Last Updated :
14 Sep, 2023
Shutdown Hooks are a special construct that allows developers to plug in a piece of code to be executed when the JVM is shutting down. This comes in handy in cases where we need to do special clean up operations in case the VM is shutting down.
Handling this using the general constructs such as making sure that we call a special procedure before the application exits (calling System.exit(0) ) will not work for situations where the VM is shutting down due to an external reason (ex. kill request from O/S), or due to a resource problem (out of memory). As we will see soon, shutdown hooks solve this problem easily, by allowing us to provide an arbitrary code block, which will be called by the JVM when it is shutting down.
From the surface, using a shutdown hook is downright straightforward. All we have to do is simply write a class that extends the java.lang.Thread class, and provide the logic that we want to perform when the VM is shutting down, inside the public void run() method. Then we register an instance of this class as a shutdown hook to the VM by calling Runtime.getRuntime().addShutdownHook(Thread) method. If you need to remove a previously registered shutdown hook, the Runtime class provides the removeShutdownHook(Thread) method as well.
Example 1 (Anonymous inner class):
Java
public class ShutDownHook
{
public static void main(String[] args)
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println("Shutdown Hook is running !");
}
});
System.out.println("Application Terminating ...");
}
}
When we run the above code, you will see that the shutdown hook is getting called by the JVM when it finishes the execution of the main method.
Output:
Application Terminating ...
Shutdown Hook is running !
Example 2
Java
class ThreadChild extends Thread {
public void run() {
System.out.println("In clean up code");
System.out.println("In shutdown hook");
}
}
class Demo {
public static void main(String[] args) {
Runtime current = Runtime.getRuntime();
current.addShutdownHook(new ThreadChild());
for(int i = 1; i <= 10; i++)
System.out.println("2 X " + i + " = " + 2 * i);
}
}
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
In clean up code
In shutdown hook
Simple right? Yes, it is.
While it is pretty simple to write a shutdown hook, one needs to know the internals behind the shutdown hooks to make use of those properly. Therefore, in this article, we will be exploring some of the ‘gotchas’ behind the shutdown hook design.
1. Shutdown Hooks may not be executed in some cases!
The first thing to keep in mind is that it is not guaranteed that shutdown hooks will always run. If the JVM crashes due to some internal error, then it might crash down without having a chance to execute a single instruction. Also, if the O/S gives a SIGKILL (http://en.wikipedia.org/wiki/SIGKILL) signal (kill -9 in Unix/Linux) or TerminateProcess (Windows), then the application is required to terminate immediately without doing even waiting for any cleanup activities. In addition to the above, it is also possible to terminate the JVM without allowing the shutdown hooks to run by calling Runtime.halt() method.
Shutdown hooks are called when the application terminates normally (when all threads finish, or when System.exit(0) is called). Also, when the JVM is shutting down due to external causes such as a user requesting a termination (Ctrl+C), a SIGTERM being issued by O/S (normal kill command, without -9), or when the operating system is shutting down.
2. Once started, Shutdown Hooks can be forcibly stopped before completion.
This is actually a special case of the case explained before. Although the hook starts execution, it is possible to be terminated before it completes, in cases such as operating system shutdowns. In this type of case, the O/S waits for a process to terminate for a specified amount of time once the SIGTERM is given. If the process does not terminate within this time limit, then the O/S terminates the process forcibly by issuing a SIGTERM (or the counterparts in Windows). So it is possible that this happens when the shutdown hook is halfway through its execution.
Therefore, it is advised to make sure that the Shutdown Hooks are written cautiously, ensuring that they finish quickly, and do not cause situations such as deadlocks. Also, the JavaDoc [1] specifically mentions that one should not perform long calculations or wait for User I/O operations in a shutdown hook.
3. We can have more than one Shutdown Hooks, but their execution order is not guaranteed.
As you might have correctly guessed by the method name of the addShutdownHook method (instead of setShutdownHook), you can register more than one shutdown hook. But the execution order of these multiple hooks is not guaranteed by the JVM. The JVM can execute shutdown hooks in any arbitrary order. Moreover, the JVM might execute all these hooks concurrently.
4. We cannot register/unregister Shutdown Hooks within Shutdown Hooks
Once the shutdown sequence is initiated by the JVM, it is not allowed to add more or remove any existing shutdown hooks. If this is attempted, the JVM throws IllegalStateException.
5. Once shutdown sequence starts, it can be stopped by Runtime.halt() only.
Once the shutdown sequence starts, only Runtime.halt() (which forcefully terminates the JVM) can stop the execution of the shutdown sequence (except for external influences such as SIGKILL). This means that calling System.exit() within a Shutdown Hook will not work. Actually, if you call System.exit() within a Shutdown Hook, the VM may get stuck, and we may have to terminate the process forcefully.
6. Using shutdown hooks require security permissions.
If we are using Java Security Managers, then the code which performs adding/removing of shutdown hooks need to have the shutdown hooks permission at runtime. If we invoke this method without permission in a secure environment, then it will result in SecurityException.
References :
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)
Similar Reads
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsi
6 min read
Main thread in Java
Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
4 min read
How to Run Java Program?
Java is a popular, high-level, object-oriented programming language that was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing various kinds of software, including web applications, desktop applications, m
2 min read
heapDump() Method of MBean in Java
The heapDump() method in Java is a solid and powerful tool for troubleshooting and analyzing the performance of Java Programs. MBeans, or Managed Beans, are the objects of Java that provide various information and control aspects of a Java Application, Such as memory usage, threading, and performanc
5 min read
javap tool in Java with Examples
javap tool The javap tool is used to get the information of any class or interface. The javap command (also known as the Java Disassembler) disassembles one or more class files. Its output depends on the options used (â-câ or â-verboseâ for byte code and byte code along with innards info, respective
2 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is
3 min read
How to Update the Java Version in Windows?
Java is a high-level, robust, object-oriented, and secure programming language that was developed in the year 1995 by Sun Microsystems (which is now part of Oracle group), and James Gosling is known as the father of Java. Â It is a general-purpose programming language intended to let programmers writ
4 min read
run() Method in Java Thread
The run() method is available in the thread class constructed using a separate Runnable object. Otherwise, this method does nothing and returns. We can call the run() method multiple times. The run() method can be called in two ways which are as follows:Using the start() method.Using the run() metho
3 min read
Java MouseListener in AWT
The Abstract Window Toolkit (AWT) in Java provides a collection of user interface components and event-handling features for creating graphical user interfaces (GUIs). User interaction is an important component of GUI programming, and the MouseListener interface in AWT is an important tool for manag
3 min read
Java WindowListener in AWT
The Abstract Window Toolkit (AWT) of Java provides a collection of graphical user interface (GUI) components for creating desktop applications. When it comes to managing window-related events, the WindowListener interface is used. The WindowListener interface provides methods for responding to windo
4 min read