Introduction
Shutdown Hooks are a specific construct that allows developers to insert code that will run when the JVM shuts down. This is useful in situations when we need to do extra clean-up actions before the VM shuts down.
In scenarios when the VM is shutting down due to an external reason (for example, a kill request from the operating system) or a resource problem, generic constructs such as guaranteeing that we execute a particular method before the programme departs (calling System.exit(0)) will not function (out of memory). As we'll see shortly, Shutdown hooks easily fix this problem by letting us give an arbitrary code block that the JVM(Java Virtual Machine) will call when it's shutting down.
Using a shutdown hook looks to be straightforward on the surface. We'll have to make a class that extends the java.lang package. Put the logic we want to perform when the VM goes down in the public void run() method of the Thread class. Then, using, we register a VM shutdown hook with an instance of this class.
addShutdownHook(Thread) function of Runtime.getRuntime(). The Runtime class also has a removeShutdownHook(Thread) function if you need to delete a previously registered shutdown hook.
Now let see its implementation with some practical examples which are mentioned below
Must Read, Multithreading in java, Duck Number in Java, Multithreading in Python
Getting Started
Let's code it out and find the output and see how simple is it to write a ShutDown Hook in java and see its application.
Example 1
public class ShutDownHook{
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
System.out.println("*** Coding Ninjas ***");
System.out.println("Shut Down Hook was running !!");
}
});
System.out.println("Application has been terminated!!");
}
}
Output
Example 2
import java.util.ArrayList;
class ChildThread extends Thread{
public void run(){
System.out.println("\nClean Up code");
System.out.println("ShutDown Hook");
}
}
public class ShutDownHook{
public static void main(String[] args){
Runtime current = Runtime.getRuntime();
current.addShutdownHook(new ChildThread());
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(5);
numbers.add(7);
System.out.print("Squares of Integers: ");
numbers.forEach((number) -> {System.out.print(number * number + " ");});
}
}
Output
Try it on online java compiler.