Shutdown hook executes before the process is gracefully shutdown. It is useful when we want to clean up resources like closing the files, network channels or want to log some useful information.
ShutdownHookDemo.java
public class ShutdownHookDemo {
public static void main(String args[]) {
System.out.println("Before adding shutdown hook");
Runtime.getRuntime().addShutdownHook(new Thread(ShutdownHookDemo::shutdownHook));
System.out.println("After adding shutdown hook");
}
static void shutdownHook() {
System.out.println("I am shuttig down..");
// perform pre-shutdown operations like closing files, network resources etc
}
}
Here we have used method references in Java 8 . Runtime class is the gateway for interacting with JRE. Since each java program must be bound to a process, before the process is gracefully exited (i.e. not forcefully killed using kill -9) then this shutdown hook can be used to perform pre-shutdown operations.
No comments:
Post a Comment