Developer

Use hooks for clean shutdowns

Make sure your application makes a proper exit: Use Java's Shutdown Hooks API. Here's a look at why and how to make use of this great tool.


Part of writing a stable, robust application is ensuring that it exits cleanly. This may involve removing temporary files, flushing I/O buffers, or terminating network or database connections. JDK 1.3 provides a framework called the Shutdown Hooks API for running such tasks when your application exits.

A shutdown hook is a thread that is run when the JVM is in the process of shutting down, either as the program exits normally—typically through System.exit()—or as a result of a termination event, such as a [Ctrl]C keypress in a console window.

How to use the hook
To create a shutdown-hook thread, you need to pass a Thread object to Runtime.addShutdownHook(). This object will be held until needed. The run() method of the Thread object should implement your task and will be called as part of the shutdown process. An anonymous Thread class is usually sufficient, as in this sample:
Runtime.getRuntime().addShutdownHook(
 new Thread()
 {
  public void run() {
   //do shutdown work here or call external method
  }
 }
);


If your application may need to remove a particular shutdown hook while the application is running, you'll need to create the Thread object and store a reference to it explicitly, which you can then pass to Runtime.removeShutdownHook() as needed.

Things to watch out for
Because all registered shutdown hooks are run concurrently, it's important that they be thread-safe. They should also terminate as quickly as possible because some systems will allow applications only a small amount of time to complete their shutdown tasks after receiving a termination event. For the same reason, it's usually not a good idea to attempt any user interaction during shutdown-hook execution.

Additional info
When you need to ensure that certain tasks run as part of your application's shutdown process, shutdown hooks offer a simple solution. You can find more information on the Shutdown Hooks API by visiting java.sun.com's Design of the Shutdown Hooks API page.

Making a clean exit
Do you have any tricks for making sure your apps make a clean exit? Share your ideas by sending us an e-mail with your suggestions or post a comment below.

 

Editor's Picks