Catching JVM Shutdown event

Shutdown hook is a mechanism provided by java for us to handle shutdown event of our applications. We can attach any piece of code to this and execute them just before JVM exits.

public class ShutDownHookTest {
public static void main(String [] args) throws Exception {
System.out.println("System Started...");

Runtime.getRuntime().addShutdownHook(new Thread( new Runnable() {
public void run() {
System.out.println("System is Shutting Down...");
}
}));

Thread.sleep(10000);
}
}


Compile and run this sample code and press Crt+C to exit the application, you can see that "System is Shutting Down" message prints before application exiting.

But we have to be careful when using this, because if the shutdown code we attach to the shutdown hook end up in an infinite loop, our application will be stuck and only way to exit will be killing the process.
 

Tribune to Heros

Tribune to Heros
We will never forget the sacrifices you made to protect our country....

Subscribe


Get Google Toolbar Button

Enter your email address:

Delivered by FeedBurner