In Java, there is a special Runtime method for this: addShutdownHook .
This allows you to initialize the thread that the JVM will attempt to start immediately before stopping. This is the place to put any cleanup you want to perform, even if you close the closing parent window of Ctrl-C. Extract from javadoc: The disconnect hook is just an initialized, but unexpanded stream. When the virtual machine starts its shutdown sequence, it will start all registered shutdown hooks in some unspecified order and allow them to start at the same time. When all hooks are finished, it will start all uninvited finalizers if output finalization is enabled. Finally, the virtual machine will stop.
The shutdown hook is a call, even if the program ends normally. In this case, clean remove the registered hook before exiting using removeShutdownHook (another method from Runtime )
EDIT:
In the case of the Windows environment, there are no real signals, but special callbacks when the system is turned off. AFAIK, the system hook is correctly called in this case, but I admit that I have never tested this. On Windows, processes can be requested to terminate in two ways:
- The PostQuitMessage function sends a WM_QUIT message to the event loop - usually the process should exit, but it can do the cleanup (equivalent to Unix SIG_TERM)
- TerminateProcess immediately stops the process and all its threads (equivalent to Unix SIG_KILL)
Console processes can use the ConsoleControlHandler, which can intercept the events of Ctrl-C, Ctrl-Break, or Ctrl-Close. The first two are generated using the keyboard, the last is generated when the user closes the console. But typically, the Oracle JVM should use the hook mechanism when it receives the Ctrl-Close event, which is handled in the same way as SIGTERM.
source share