Question: I would like to know how my Java program can catch when someone
shuts down JVM...
Answer: Starting with Java, there is Runtime.addShutdownHook().
It is for cleanup only...
From Java API: "A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled.
Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.
Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.
Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook. Attempting either of these operations will cause an IllegalStateException to be thrown.
Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook."
In rare circumstances the virtual machine may abort, that is, stop
running without shutting down cleanly. This occurs when the virtual machine is
terminated externally, for example with the SIGKILL signal on Unix or
the TerminateProcess call on Microsoft Windows. The virtual machine may
also abort if a native method goes awry by, for example, corrupting internal
data structures or attempting to access nonexistent memory. If the virtual
machine aborts then no guarantee can be made about whether or not any shutdown
hooks will be run.
more read in Java API
Java Code examples on
1779 bytes more | 13 comments | | Score: 2.5