animesh kumar

Running water never grows stale. Keep flowing!

shutdown hooks in java

with one comment

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.

Read more >>

About these ads

Written by Animesh

March 28, 2011 at 4:41 pm

Posted in Technology

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. Nice post thx :)

    shivachenthil

    March 29, 2011 at 11:18 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 204 other followers

%d bloggers like this: