Java Shutdown HookThe shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook. When does the JVM shut down?The JVM shuts down when:
The addShutdownHook(Thread hook) methodThe addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine. Syntax: The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example: Runtime r = Runtime.getRuntime();
Factory methodThe method that returns the instance of a class is known as factory method. Simple example of Shutdown HookOutput:Now main sleeping... press ctrl+c to exit shut down hook task completed.. Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.Same example of Shutdown Hook by annonymous class:Output:Now main sleeping... press ctrl+c to exit shut down hook task completed.. |