Question of the Week #78
What does a shutdown hook do and how can one be created?
4 messages · Page 1 of 1 (latest)
What does a shutdown hook do and how can one be created?
Java allows creating shutdown hooks which are run when the Java program terminates.
Note that shutdown hooks are not executed in case of an abrupt termination (e.g. the JVM crashing or a SIGKILL).
A shutdown hook can be created by passing an unstarted Thread to Runtime#addShutdownHook:
Thread shutdownHook = new Thread(()->{
System.out.println("This should be run when the application stops");
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
Shutdown hooks can be used to clean up some things. For example, if a file is needed as long as the application is running, it could be deleted up in a shutdown hook.
Path tempFile = Files.createTempFile("myapp",".tmp");
System.out.println("created temporary file: " + tempFile);
Thread shutdownHook = new Thread(()->{
try{
System.out.println("application stops - trying to delete temp file");
Files.delete(tempFile);
} catch(IOException e){
e.printStackTrace();
}
});
Runtime.getRuntime().addShutdownHook(shutdownHook);
A shutdown hook gets executed when the program exits. One can be created using Runtime#addShutDownHook which takes in a thread
A shutdown hook is a mechanism in Java that allows a program to execute a specific block of code just before the Java Virtual Machine (JVM) terminates. This can be useful for performing cleanup tasks, such as closing resources, releasing locks, or logging information, when the program is about to exit. Shutdown hooks are particularly useful in scenarios where the program needs to perform some critical operations before shutting down, such as saving unsaved data or releasing system resources.
How to Create a Shutdown Hook?
To create a shutdown hook, you need to create a thread that will execute the desired code when the JVM is shutting down. This is done by creating a Thread object that implements the Runnable interface and adding it to the JVM's shutdown hook list using the Runtime.getRuntime().addShutdownHook() method.
Here's an example of how to create a shutdown hook:
public class ShutdownHookExample {
public static void main(String[] args) {
// Create a thread that will execute when the JVM shuts down
Thread shutdownHook = new Thread(new Runnable() {
@Override
public void run() {
// Code to be executed when the JVM shuts down
System.out.println("Shutdown hook executed!");
// Perform cleanup tasks, release resources, etc.
}
});
// Add the thread to the JVM's shutdown hook list
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}