在最终确定最佳实践中关闭连接? [英] Is closing the connection in finalize best practice?

查看:146
本文介绍了在最终确定最佳实践中关闭连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么要实现finalize()?


我看到一些java文件与以下代码:

  public void finalize(){
if(conn!= null){
try {
conn.close();
} catch(SQLException e){
}
}
}




  • finalize 方法最佳实践中关闭连接 / li>
  • 是否足够关闭连接或者需要关闭其他对象,例如 PreparedStatement
  • 从Java 7,关闭资源的最佳实践是使用try-with-resource:



    http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


    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?

    解决方案

    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

    这篇关于在最终确定最佳实践中关闭连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆