Thursday, 17 March 2016

How to make sure that if someone has written System.exit() at some part of application then before system shutdown all the resources should be released ?


Use : Runtime.getRuntime().addShutdownHook(Thread hook)
It registers a new virtual-machine shutdown hook.

JVM shuts down in response to two kinds of events : 
 1. The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked.
  OR
 2. The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user log off or system shutdown.

A shutdown hook is simply an initialized but unstarted thread.
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled.
Finally, the virtual machine will halt.

Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.