Search code examples
javadatabase-connectionfinalizer

Is closing the connection in finalize best practice?


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?

Solution

  • 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