Java - Shutdown Hooks

Ömer Kurular
3 min readMay 1, 2021

Shutdown hooks in Java are simply threads that will execute before normal execution of a program terminates. Let’s look at how and when to use them.

How to create your own shutdown hook?

You can create your custom shutdown hook easily by extending Thread class as your custom hook will also be a thread. Then you need to implement what you need to do inside overriden run method. In the code snippet below, CustomShutdownHook class I created will check if the network connection is still open and will close it if so.

public class CustomShutdownHook extends Thread {
private NetworkService networkService;

public CustomShutdownHook(NetworkService networkService) {
this.networkService = networkService;
}

@Override
public void run() {
if (networkService.isConnected()) {
networkService.disconnect();
}
}
}

How to register your custom shutdown hook?

When you create your own shutdown hook, you need to register it so it will be taken into account when JVM is shutting down, and registering it is as easy as calling a simple method and passing your hook thread into it.

Here is a simple code snippet that will show you how.

Runtime.getRuntime().addShutdownHook(customShutdownHook);

When is your custom shutdown hook called?

As its name suggest, a shutdown hook is called when the related process is about to exit. But there are some limitations to it. Not every shutdown scenario will trigger our custom hook. Here are the cases that will trigger our hook before exit.

  1. Exiting after normal flow of program ends. It means, every non-daemon thread completes its execution.
public static void main(String[] args) {
// ...
// ...
// Here our program is about to end and our hook will run soon.
}

Another example related to daemon threads

public class CustomShutdownHook extends Thread {
private String text;

public CustomShutdownHook(String a) {
this.text = a;
}

@Override
public void run() {
System.out.println(text);
}
}
// Example 1, infinite loop
public static void main(String[] args) {
Thread nondaemonThread = new Thread(() -> {
while (true);
});
nondaemonThread.start();
Runtime.getRuntime().addShutdownHook(new CustomShutdownHook("someText"));
}
// Example 2, prints "someText"
public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
while (true);
});
daemonThread.setDaemon(true); // notice the difference here
daemonThread.start();
Runtime.getRuntime().addShutdownHook(new CustomShutdownHook("someText"));
}

In the Example 1, the thread is non-daemon and our hook will not be triggered as thread executes an infinite loop. In the Example 2, we set the thread as daemon and eventhough it executes infinite loop, our hook will be triggered and prints the given text.

2. System.exit() is called.

public static void main(String[] args) {
// ...
// ...
System.exit(0);
/* This call will cause our program to stop further execution
and trigger shutdown hook. */
}

3. User controlled exit with Ctrl + C

Consider running your program in a console and you signal it with Ctrl+C to terminate it. It will trigger the shutdown hooks you registered.

There is also another significant issue that when you have multiple shutdown hooks registeres, they will not execute in order you register them.

When should you benefit shutdown hooks?

There are cases which you can create and register custom hooks. When you have specific backup tasks to execute before exiting such as closing network connections, you can take advantage of it. But here I need to say that, you better do these kind of cleaning task according to your program logic e.g when exit button clicked on your UI or specific user command provided in console, you handle these kind of cleaning task and do not leave them unhandled by relying on shutdown hooks. For example, imagine a situation where your shutdown hooks are not executed because kill -9 singal is used or OS dies unexpectedly, your cleaning process inside custom hooks will not execute and connections may stay open after program dies. To prevent these, you handle your all logic in the normal flow and let your hooks guarantee what you want to achieve before exiting. (Check first snippet)

In this tutorial, I talked about shutdown hooks in Java. I hope you will find it useful and like it.

--

--

Ömer Kurular

I am Ömer and currently working as a full-time software engineer. I will share my knowledge with you I gained through years of professional and self working.