animesh kumar

Running water never grows stale. Keep flowing!

Posts Tagged ‘ShutDownHook

shutdown hooks in java

with one comment

[tweetmeme source=”anismiles” only_single=false

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

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.


Written by Animesh

March 28, 2011 at 4:41 pm

Posted in Technology

Tagged with ,