Sunday, June 24, 2012

Java Shutdown Hooks


What is Shutdown Hook
We know that in some situations we will have to do some clean-up operations  when the user shuts down our application. Sometimes  the user does not always follow the recommended procedure to exit the application. Java provides an API for programmers to execute code in the middle of the shutdown process,this in turn make sure that our clean-up code is always executed.
This article shows how to use a shutdown hook to guarantee that clean-up code is always run, regardless of how the user terminates the application.
Shutdown Hook is a simple thread which is registered in JVM.
It can be registered by using addShutdownHook (Thread hook). It is a method of java.lang.Runtime class
Some Important points to be remembered:
1) When JVM starts shut down process,  it starts execution of its all registered shutdown Hook  concurrently.
2) You can use Shutdown hook if you want to display messages or execute some code before JVM shut down.
3) We cannot register Shutdown Hook during shut down process. It will through IllegalStateException.
4) We cannot guaranteed that during JVM shutdown process all the registered Shutdown hook complete their execution.
5) If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.
Now lets see one complete example which will demonstrate the use of shutdown hook.
Example
The below example code provides two classes
1)  ShutdownHookDemo
and
2) A subclass of Thread named ShutdownHook.
After instantiation of the public class ShutdownHookDemo , its begin method is called. The begin method creates a shutdown hook and registers it with the current runtime.
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
When the user press any key, the program exits. But still the the virtual machine will run the shutdown hook and print the message “Im Shutting down” 

lets a create class which actually does the job to be done while VM is shutting down
Output
Im inside start
Im Shutting down
When finalizers will run, before, during, or after shutdown hooks?
Finalization-on-exit processing is done after all shutdown hooks have finished. Otherwise a hook may fail if some live objects are finalized prematurely.

For more information please go through this link