English 中文(简体)
是否在最后确定最佳做法方面关闭联系? [复制]
原标题:Is closing the connection in finalize best practice? [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Why would you ever implement finalize()?

我看到了一些java文档,其代码如下:

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?
最佳回答
问题回答

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.

相反,你们应该把资源用于一个整体,例如:

try {
  acquire resource
}
finally {
  if (resource was acquired)
    release it
}

如果不是这样,最终确定者不太可能被及时传唤。 明确和肯定地清理你们的资源。

/* Acquire resource. */
try {
  /* Use resource. */
}
finally {
  /* Release resource. */
}

一旦获得联系标语,就利用这个标语执行准备的声明/声明/声明,这些标语被放在一个试卷栏中,然后将房屋清理工作,如关闭雕像,并排在座。

指称:

 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();
 }




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签