The Java virtual machine shuts down in response to two kinds of events:
- A program terminates normally when the last non-daemon thread terminates or when the
exit method is called (equivalently, System.exit ), or - The virtual machine terminates in response to a user interruption, for example,
^C input or a system-wide event, such as logging out or shutting down the system.
...
Shutdown hooks start at a difficult time in the life cycle of a virtual machine and therefore must be encoded in defense. They should, in particular, be written as thread safe and avoid deadlocks as much as possible. Neither should they blindly rely blindly on services that could register their own disconnection hooks and, therefore, can themselves in the shutdown process. For example, attempts to use other thread-based services, such as an AWT event flow, may result in deadlocks.
Shutdown hooks should also shut down quickly. When the program calls exit , the expectation is that the virtual machine will quickly shut down and exit. When a virtual machine shuts down due to a user logging off or shutting down the system, the base operating system can only allow a fixed period of time during which it is necessary to shut down and log off. Therefore, it is impractical to try any interaction with the user or to perform long-term calculation in the stop cache.
...
In rare cases, a virtual machine can interrupt work, that is, stop working without turning it off. This happens when the virtual machine shuts down externally, for example, with a SIGKILL signal on Unix or a TerminateProcess call on Microsoft Windows. In addition, the virtual machine may interrupt if the native method goes awry, for example, corrupting internal data structures or trying to access non-existent memory. If the virtual machine is interrupted, then there can be no guarantee as to whether any shutdowns will be performed.
"Finishing hooks should also finish their work quickly."
Relying on everything that may take some time to complete your work, or blocking unlimited time on user inputs such as JOptionPane dialogs, is not what you should do in your shutdown. p>
"Attempts to use other thread-based services, such as AWT event flow, for example, can lead to deadlocks"
Swing runs on top of AWT, whose main event dispatch thread can also fail. Trying to use Swing or AWT when shutting down can not only lead to dead locks, but it may not work at all.
"If the virtual machine is interrupted, then there can be no guarantee as to whether any terminating hooks will be executed."
There is no guarantee that your user can even receive your message, because the final hooks are guaranteed only when it is completed or completed - not when stopped or interrupted.