This Java tip illustrates a method of determining when the application is about to exit. An application may be terminated in various situations. For example, normal termination can be caused by a call to System.exit(), the completion of the last non-daemon thread, or the interruption of the application (control-C) by the user. Abnormal termination (which does not cause the shutdown threads to be started) is caused some major fault in the Java virtual machine or native library. When an application is terminated normally, the application first starts terminated any registered threads, waits for them to complete and then finally exits.

  Runtime.getRuntime().addShutdownHook(new Thread() {
        // This method is called during shutdown
        public void run() {
            // Do shutdown work ...
        }
    });