eclipse中的资源泄漏警告

Ret*_*rub 15 java eclipse resource-leak

在Eclipse我收到警告Resource leak: 'ps' is not closed at this location,我不明白.

在我的Java代码中,我将"ps"声明为Prepared Statement,并且我多次使用(并关闭)它.然后我有以下顺序:

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
        };
}
Run Code Online (Sandbox Code Playgroud)

"资源泄漏" - 警告来自其他部分的"更新" - 声明.如果我ps = null在启动try块之前设置,则没有警告.

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

这是理解还是java/eclipse的问题?

Ale*_*exR 11

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

// 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.
Run Code Online (Sandbox Code Playgroud)

我确实不知道为什么if/else声明的存在导致警告出现或消失.但java 7推荐使用我上面描述的可自动关闭资源的方法,所以试试这个.


Ale*_*yak 3

我认为,这是您使用的检查器的问题。

将您的代码分成initialization和use块。另外,从初始化块中抛出异常(或提前返回)。use这样,当您在块后释放资源时,无需检查 null

// initialization
// Note that ps is declared final.
// I think it will help to silence your checker
final PreparedStatement ps;

try {
    if( bedingungen ... ) {
        ps = c.prepareStatement("UPDATE 1 ...");
    } else {
        ps = c.prepareStatement("UPDATE 2 ...");
    }
} 
catch (SQLException e) {
    log.error("Problem creating prepared statement, e );
    throw e;
}

// use
try {
    ps.executeUpdate();
} catch (SQLException e) {
    log.error("Problem decrementing palets on " + srcElement.getName() + 
        ": " +    e.getMessage());
}
finally {
    try {
        ps.close();
    } catch (SQLException e) {
        log.warn("Error closing PreparedStatement: " + e.getMessage());
    };
}
Run Code Online (Sandbox Code Playgroud)