Suppose I've got a Java application that opens a database connection. Normally I'd give a connection.close() inside a finally block, but this block would not be performed within the situation of the kill operation, or other abnormal termination, wouldn't it? Are there more safeguards which i, like a programmer, could make to be able to close the bond correctly prior to the application exits?
You should think about the Runtime.addShutdownHook() way of Java (http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). It enables you to definitely give a hook that'll be known as once the virtual machine terminates. Technology-not only to call a cleanup routine.
That might be for any TERM signal though. A KILL signal will get rid of the process and today let it inflict cleanup.
Killing a course will ultimately timeout a
TCP stream out of your program for your
[Oracle|SQL Server|MySQL|PostgreSQL] server.
The server might find it and rollback any pending transactions.
If something exterior kills your program, there is nothing that you can do about this. Clearly they desired to stop it, so how will you prevent them?
I would advise a shutdown hook, however the Javadocs condition:
In rare conditions the virtual machine may abort, that's, stop running without shutting lower cleanly. This happens once the virtual machine is ended externally, for instance using the
SIGKILLsignal on Unix or even the
TerminateProcess callon Microsoft Home windows. The virtual machine could also abort if your native method goes awry by, for instance, corrupting internal data structures or trying to gain access to nonexistent memory. When the virtual machine aborts then no guarantee can be created if any shutdown hooks is going to be run.
- You should not have to call connection.close() on application shut-lower, since all open files is going to be closed instantly through the operating-system.
- Also, the Connection's finalize() method ought to be run before application shut-lower instantly (when the shut-lower is common, not ABORTed), which should close the bond.
- Regardless, you are able to register shutdown-hooks, to complete any clean-up you need (again, is going to be run in normal shutdown cases, not ABORTs).
Whenever you really get wiped out (
kill -9 on UNIX), you can't do anything whatsoever against that.
finally-block is easily the most that you can do, see SO: In Java, is the “finally” block guaranteed to be called (in the main method)? for particulars.
Some degree of abnormal termination is inevitable. How does one catch the big event from the energy cable being drawn around the server?