Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is closing the connection in finalize best practice? [duplicate]

Possible Duplicate:
Why would you ever implement finalize()?

I saw some java files with the following code:

public void finalize() {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
        }
    }
}
  • Is closing a Connection in the finalize method best practice?
  • Is it enough to close the Connection or does one need to also close other objects such as PreparedStatement?
like image 403
developer Avatar asked May 13 '12 20:05

developer


3 Answers

From Java 7, the best practice for closing a resource is to use a try-with-resource :

http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

like image 96
Jérôme Radix Avatar answered Sep 17 '22 23:09

Jérôme Radix


No, that is not "best practice", or even "passable practice". You have no guarantee when if at all finalizers are called, so it won't work.

Instead you should scope out resources to a block, like this:

try {
  acquire resource
}
finally {
  if (resource was acquired)
    release it
}
like image 37
Jon Avatar answered Sep 20 '22 23:09

Jon


No, the finalizer is unlikely to be called in a timely manner, if ever. Clean up your resources explicitly and certainly.

/* Acquire resource. */
try {
  /* Use resource. */
}
finally {
  /* Release resource. */
}
like image 31
erickson Avatar answered Sep 20 '22 23:09

erickson