日食中的资源泄露警告 [英] Resource leak warning in eclipse

查看:294
本文介绍了日食中的资源泄露警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Eclipse 我收到警告资源泄漏:'ps'未关闭在这个位置

在我的 Java 代码中,我将ps声明为一个准备的声明,我使用(并关闭)它很多次。然后我有以下顺序:

In my Java code I declare the "ps" as a Prepared Statement and I use (and close) it many times. Then I've the following sequence:

try {
    if(condition) {
        ps = c.prepareStatement("UPDATE 1 ...");
    } else {
        ps = c.prepareStatement("UPDATE 2 ...");
    }
    ps.executeUpdate();
} catch (SQLException e) {
    // exception handling
} finally {
    if (null != ps) 
        try { 
            ps.close(); 
        } catch (SQLException e) { 
            // exception handling
        };
}

资源泄露 - 警告来自更新 - 声明其他部分。
如果我在开始尝试块之前设置了 ps = null ,那么没有警告。

The "Resource leak"-Warning comes on the "Update"-Statement in the else section. If I set ps = null before I start the try block, there is no warning.

如果第二个UPDATE-Statement被注释掉,则不会显示任何警告。

If the second UPDATE-Statement is commented out, no warning will be shown.

这是一个理解或java / eclipse问题吗?

Is that an understanding or a java / eclipse problem?

推荐答案

如果您有此警告,则使用Java 7.在这种情况下,您不应该关闭实现 AutoClosable 你自己您应该在 try statementcommented的特殊初始化部分初始化这些资源:

If you have this warning you are using Java 7. In this case you should not close the resource that implements AutoClosable yourself. You should initialize those resources in special initialization section of try statementcommented:

// decide which update statement you need:
// (your if should be here)
String update = ....;
try (
     ps = c.prepareStatement(update);
) {
   // use prepared statement here.
} catch (SQLException) {
   // log your exception
   throw new RuntimeException(e);
}
// no finally block is needed. The resource will be closed automatically.

我确实不知道为什么存在 if / else 语句导致警告出现或消失。但是,java 7建议使用上面描述的可关闭资源的方式,所以请尝试这样。

I indeed do not know why presence of if/else statement causes the warning to appear or disappear. But java 7 recommends the way to work with auto closable resources that I described above, so try this.

这篇关于日食中的资源泄露警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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