Shutdown Hooks for JVM Applications
Firstly, we look at hook definition in programming. Maybe you heard the term hook when using React JS.
“In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a hook.” — Wikipedia
In this post, we will learn how JVM can notify us if the Java process shut down. For this purpose, we can use shutdown hooks.
Shutdown hooks are useful in some scenarios. For example, when you need to clean up resources at the end of the program, you can use this feature.
The shutdown hook is basically a thread. Threads are initialized and not executed. As soon as the JVM shuts down normally, the threads start to work. If JVM stops abruptly, shutdown hooks won’t be worked.
In the code below, there is a thread that has a Runnable. This runnable prints a message which “Program exits”. After defining the thread, we use the Runtime API of Java and give a thread as a parameter to addShutdownHook(Thread thread) method.
Thread shutDownHookThread = new Thread(() -> {
System.out.println("Program exits");
});
Runtime.getRuntime().addShutdownHook(shutDownHookThread);
The output will be “Program exits” when we stop the Java program by using Ctrl + C.
Here are some tips about shutdown hooks:
- One of the examples of JVM unexpected exits can be out of memory problem. In this case, shutdown hooks won’t execute.
- It is not possible to use the same thread again for the shutdown hook. If you add the same thread twice, you will get an IllegalArgumentException and an exception message that says “Hook previously registered”.
- When multiple shutdown hooks exist, they are executed in random order.
- If you want to remove a shutdown hook, you can use Runtime.getRuntime().removeShutdownHook(Thread hook) method.