问题
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 thefinalize
method best practice? - Is it enough to close the
Connection
or does one need to also close other objects such asPreparedStatement
?
回答1:
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
回答2:
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
}
回答3:
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. */
}
回答4:
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();
}
来源:https://stackoverflow.com/questions/10574802/is-closing-the-connection-in-finalize-best-practice