Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: how to call a method when the process has been stopped (is it even possible?)

Tags:

java

shutdown

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.

like image 520
jbu Avatar asked Jul 16 '09 04:07

jbu


1 Answers

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.

like image 166
Chris Arguin Avatar answered Nov 14 '22 21:11

Chris Arguin