Cody
Cody

Reputation: 890

Any Shutdown Hook when application is "Force Closed"?

Is there any way to make the program go through the shutdown hook if the user forces java to close (through the task manager or by closing the corresponding batch file).

My program currently runs and executes well, if the user closes the GUI then it goes through a set of steps to disconnect from the database. However, if the user closes the Java or the batch file (running side by side with the GUI) then the connection to the database isn't closed.

Is it possible to somehow force the connection closed and maybe even delete something from the tables? The batch file will probably not be an issue when I jar the program but the process killing still will.

Upvotes: 4

Views: 4280

Answers (1)

jefflunt
jefflunt

Reputation: 33954

Nope.

The shutdown hook will react to Ctrl+C, normal closes, user logouts, and normal system shut downs (which request a graceful shutdown of all applications).

However, if someone is force-closing the app it's assumed that that's what you actually want - immediate termination with no further notice. This question has been asked many times, and is confused by the behavior of many applications that, when they are asked to force-close, they actually take a long time to finally terminate. This is because in the OS's efforts to release all resources, some resources (especially certain I/O and/or file resources) don't let go immediately.

In testing an app that starts, and is intended to be running until a graceful shutdown (e.g. server software) you should run it at the console/command-line, and press Ctrl+C to stop the program (which will run the shutdown hook) rather than using Task Manager, or KILL -9.

Furthermore, there's nothing Java could even do about it if it wanted to. A force-close happens at the OS level, at which point it releases the memory, file and I/O handles in use, etc. Java does not (nor does any other program) have control over a force-close. At this point, the OS is taking charge.

Upvotes: 7

Related Questions