Java / Concurrent collections
What is Java Shutdown Hook?
The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. So if you want to execute some code before JVM shuts down, use shutdown hook.
public class MyShutdownHook { public static void main(String[] args) { System.out.println("Executing main Thread."); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { System.out.println("Executing Shutdown hook Thread."); } })); System.out.println("Exiting main thread."); } }
JVM shutdown sequence has 2 phases.
- All registered shutdown hooks are started in some unspecified order and allowed to run concurrently until they finish.
- All un-invoked finalizers are run if finalization-on-exit has been enabled.
More Related questions...