I want it so when my users start my program from the command line and then kill the process (ctrl+c, for example) the program will shutdown gracefully by closing all its connections. Is this even possible? I can't just have it call a method upon closing like a GUI can? This program has no GUI.
Please let me know.
Here is a pretty good guide to signal handling in Java. It covers shutdown and termination cases as well, including Ctrl-C.
The specific call you want is in the Runtime, addShutdownHook.
There are still specific cases that you cannot handle... there is usually some way for the OS to just outright kill the application without giving it a chance to save itself. You can't cover every case through this mechanism. To quote the JavaDoc
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With