You can attach a shutdown quota to the VM, which starts whenever the VM shuts down:
The Java virtual machine shuts down in response to two kinds of events:
The program exits normally when the last non-daemon thread exits or when the exit method is called (equivalently, System.exit) or
The virtual machine terminates in response to a user interruption, for example, entering Ctrl + C or a system-wide event, such as logging out or shutting down the system.
The stream you pass as the terminating hook must follow a few rules, so read the related documentation carefully to avoid any problems. This includes thread safety, quick thread termination, etc.
In addition, as Jesper commentator notes, terminating hooks are guaranteed to start when the virtual machine is shut down normally, but if the VM process terminates by force, they do not. This can happen if the inline code spins or if you force the process to kill -9 ( kill -9 , taskkill /f ).
But in these scenarios, all bets are turned off anyway, so I would not think too much about it.
Joey Oct 23 '09 at 7:52 2009-10-23 07:52
source share