Week 78 — What does a shutdown hook do and how can one be created?
Question of the Week #78
What does a shutdown hook do and how can one be created?
4 Replies
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
:
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.
📖 Sample answer from dan1st
A shutdown hook gets executed when the program exits. One can be created using Runtime#addShutDownHook which takes in a thread
Submission from laur.gg
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);
}
}
⭐ Submission from xoticx._
A shutdown hook is a function wich you can use to execute a process during the shutdown.
For a shutdown hook you will need a new thread wich runs your code.
That one will be enabled during the shutdown.
Example:
⭐ Submission from ufo.dev