Shutdown Hooks
by
, September 21st, 2011 at 01:43 AM (3641 Views)
Shutdown hooks are threads to be run when the JVM is about to terminate. This can happen if all non-daemon threads have finished execution, System.Exit() has been called, or if the user is logging off/shutting down their OS among other operations.
So to play around, I decided to write a simple shutdown hook that would print out "goodbye!" when the JVM was shutting down. The main program would spawn a number of threads which each would stay alive for some number of time. After a while, all the threads will finish execution and the "goodbye!" will be printed to the console.
The hook is just a Thread object which hasn't been run yet. You can register the hook to be a shutdown hook using the Runtime class.
public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("goodbye!"); } }); Thread threads[] = new Thread[100]; Integer lock = new Integer(1); for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread() { @Override public void run() { try { Thread.sleep((long) (5000 * Math.random())); } catch (InterruptedException e) { e.printStackTrace(); } } }; threads[i].start(); } }
Note: I would STRONGLY recommend reading the Javadoc for addShutdownHook! It has some very important points that deal with how to write shutdown hooks, such as they must be thread safe and not incur deadlocks, as well as being able to execute quickly. It also provides information on when and if the shutdown hook will be called (for example a call to Runtime.halt will not run shutdown hooks).
Some good uses of shutdown hooks:
1. Safely closing open streams.
2. Provide any last-minute logging.
3. "Auto-save" configurations.
Bad uses:
1. Anything asking for user interaction
2. Running computationally time consuming code
3. Handling Events.
Probably providing an "auto-save" or "recovery mode" to your application is the best use of a shutdown hook. I look forward to seeing what uses others have come up with.
Happy Coding