When the user closes the application, the application must delete the
temporary file. We hope that the user will always click the Exit button--by
doing so, the shutdown method (which deletes the temporary file) will always be
called. However, the temporary file will not be deleted if the user closes the
application, by clicking the X button of the frame or by some other means.

Listing 3 offers a solution to this. It modifies the code in Listing 2 by
providing a shutdown hook. The shutdown hook class is declared as an inner
class so that it has access to all of the methods of the main class. In Listing 3,
the shutdown hook's run method calls the shutdown
method, guaranteeing that this method will be invoked when the virtual machine
shuts down.

Now, start the small application given in Listing 3. Check that the
temporary file is always deleted, even if you abruptly shut down the
application.

Summary

Sometimes we want our application to run some clean-up code prior to
shutting down. However, it is impossible to rely on the user to always quit
properly. The shutdown hook described in this article offers a solution that
guarantees that the clean-up code is run, regardless of how the user closes the
application.