Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling abnormal Java program exits

Suppose I have a Java application that opens a database connection. Normally I would add a connection.close() in a finally block, but this block wouldn't be executed in the case of a kill operation, or any other abnormal termination, would it? Are there any other precautions that I, as a programmer, can make in order to close the connection properly before the application exits?

like image 483
Ariod Avatar asked Sep 13 '26 02:09

Ariod


1 Answers

You should look at the Runtime.addShutdownHook() method for Java (http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). It allows you to add a hook that will be called when the virtual machine terminates. You can use it to call a cleanup routine.

That would be for a TERM signal though. A KILL signal will kill the process and not allow it to do any cleanup (because the KILL signal cannot be caught or ignored by the receiving process).

like image 57
Chris Dail Avatar answered Sep 14 '26 17:09

Chris Dail