8

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?
Community
  • 1
  • 1
developer
  • 9,116
  • 29
  • 91
  • 150
  • As per [Effective Java](http://www.informit.com/articles/article.aspx?p=1216151&seqNum=7) - the best practice is to 'Avoid finalizers' – tenorsax May 13 '12 at 20:16
  • You may find [Which should I close first, the PreparedStatement or the Connection?](http://stackoverflow.com/q/2363785/1048330) useful. – tenorsax May 13 '12 at 20:32

4 Answers4

9

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

Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40
5

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
}
assylias
  • 321,522
  • 82
  • 660
  • 783
Jon
  • 2,043
  • 11
  • 9
2

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. */
}
erickson
  • 265,237
  • 58
  • 395
  • 493
-2

Once the Connection object is obtained, use it to execute the PreparedStatement/Statement/CallableStatement which is placed in a try block, then put the house-cleaning jobs like closing the statment, and the conn.

eg:

 try{

    Connection conn = DriverManager.getConnection(url,username,password);

    PreparedStatement pStat = conn.prepareStatement("Drop table info");

    pStat.executeUpdate();
      }
       catch(Exception ex){
        }

   finally(){

     pStat.close();
     conn.close();
 }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • 1
    Variable scopes are incorrect here; this won't compile. In this example, two try-finally blocks are called for, one nested in the other. – erickson May 14 '12 at 03:59