System Shutdown

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 newAPIs to the ever-growing Java platform. The 1.3 version of the Java 2SDK 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 whenit is terminated by the operating system. Before exiting, the JVMwill execute all threads that have been registered withaddShutdownHook() in an unspecified order.

You should make sure thesethreads are short-lived and avoid deadlocks because the JVM may not beallowed too much time to shut down if terminated by an operating systemshutdown. There is no way to determine if a shutdown hook thread isbeing executed due to a normal program exit or an external event.However, if your Java program is a Unix daemon or NT service, it willonly exit due to an external event and a shutdown hook can assume thateither the operating system is shutting down or the program is beingexplicitly killed by the user.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: