The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Shutdown hooks

Posted by Matt Gerrans on November 21, 2001 at 4:11 AM

> How does a Runtime.addShutdownHook() work? and can a hook ( be made to )run even after the JVM is shutdown?

My understanding of the shutdown hook is that it allows you to run a thread right before the JVM shuts down and the JVM doesn't finish shutting down until all the shutdown hooks have finished (or some outside force causes the JVM to abort even before they are finished). This allows you to quickly clean up things (such as the usual "would you like to save" type thing when closing an editor) in the event of an unexpected (or even expected, I guess) shutting down of the VM. If you take too long in your shutdown thread (for example, the Ramdisk backup mentioned earlier might be risky if it is pretty big), it may be unceremoniously terminated before finishing. This is because the VM may try to be courteous to your process (by providing the shutdown hook), the OS, which has politely asked the VM to shutdown may get testy after a bit of waiting and put its foot down (that is forcibly terminate the process, rather than asking the process to close itself).

If you have used Windows, you've probably (too often) seen this scenario: you have some program freezing up the system and decide to shutdown via task manager after Ctl-alt-del. After about 20 seconds a dialog pops up saying a program is not responding and you have the choice to kill it or wait. What happened was Windows broadcast the shutdown request message (WM_ENDSESSION) to all processes, but one (or more) did not shutdown as requested and Windows is weary of waiting. Now if you choose to end it, the process will simply be terminated. If that process was a JVM, then when it first got the shutdown request from Windows, it would have started shutting down and started all the registered shutdown hook threads. If any of the hooks had taken to long and were still grinding away, they would then be in the dangerous position of potentially being croaked mid-task.

Now, you could do a Runtime.exec() to start some process in your shutdown hook, but this may be a risky thing to do, because you don't know if only the JVM is shutting down, or if the whole OS is.

As is often the case in nature, ontology recapitulates phylogeny: what happens inside the JVM is much like what happens in the OS outside of it (and you sure can't run any processes on the OS after you've really lost your patience and plulled the plug out of the wall).

- mfg


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us