shutdown hooks in java
You know what? You can add your custom hooks to JVM to be called when JVM shuts down. Interesting… no?
What happens is very simple: you create a Thread and write you logic in there, and then register this Thread to the Runtime instance. Here is a sample:
public class JVMShutdownTest {
public static void main(String[] args) {
// Add a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
System.out.println ("closing down the shop...");
}
});
// Exit now
System.exit(0);
}
}
output will be: closing down the shop…
This attached Thread is initialized but not yet started. When JVM starts to shut down, it starts all registered hooks in an uncontrollable (that is, there is no way to enforce your will) order, and all of them run concurrently.
One thing you must take in consideration is that these hooks get executed at a very delicate time and so you must keep them light, thread-safe and independent of heavy dependencies. Thumb rule: hooks must finish quick.





Nice post thx
shivachenthil
March 29, 2011 at 11:18 am