Is there an API that I can use to sense that the system is shutting down?
Up until just recently the answer was no. But Sun keeps on adding new
APIs to the ever-growing Java platform. The 1.3 version of the Java 2
SDK adds the addShutdownHook(Thread hook) method to java.lang.Runtime.
This method registers a thread to execute when the JVM shuts down.
The JVM will shut itself down when your program exits normally or when
it is terminated by the operating system. Before exiting, the JVM
will execute all threads that have been registered with
addShutdownHook() in an unspecified order.
You should make sure these
threads are short-lived and avoid deadlocks because the JVM may not be
allowed too much time to shut down if terminated by an operating system
shutdown. There is no way to determine if a shutdown hook thread is
being executed due to a normal program exit or an external event.
However, if your Java program is a Unix daemon or NT service, it will
only exit due to an external event and a shutdown hook can assume that
either the operating system is shutting down or the program is being
explicitly killed by the user.