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

▼魔方 西西 提交于 2019-12-05 22:51:13

问题


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?

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!