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

4

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?
Galloromance answered 13/5, 2012 at 20:5 Comment(2)
As per Effective Java - the best practice is to 'Avoid finalizers'Vitiligo
You may find Which should I close first, the PreparedStatement or the Connection? useful.Vitiligo
L
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

Lurlinelusa answered 13/5, 2012 at 20:32 Comment(0)
J
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
}
Jemappes answered 13/5, 2012 at 20:32 Comment(0)
W
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. */
}
Wicked answered 13/5, 2012 at 20:39 Comment(0)
N
-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();
 }
Numerate answered 13/5, 2012 at 20:40 Comment(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.Wicked

© 2022 - 2024 — McMap. All rights reserved.