Java
Shutdown Hook
In Java, a
shutdown hook is a thread that is registered with the Java Virtual Machine
(JVM) to perform cleanup tasks or release resources when the JVM is shutting
down. Shutdown hooks are useful for ensuring that certain operations are
executed before the program terminates, regardless of whether it exits normally
or due to an unexpected error.
Example 01:
package com.java.Multi_threading;
public class ShutdownHookExample {
public static void main(String[] args) {
// Registering a shutdown hook using Runtime
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// Code to be executed during shutdown
System.out.println("Shutdown hook executed");
}));
// Rest of your program
System.out.println("Program is running");
// Simulate a program that does some work
for (int i = 0; i < 5; i++) {
System.out.println("Working... " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Exiting the program
System.exit(0);
}
}
0 Comments