eclipse中的资源泄漏警告

Eclipse我收到了一个警告Resource leak: 'ps' is not closed at this location我不明白的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 }; } 

“资源泄漏” – 警告来自else部分的“更新” – 声明。 如果我在启动try块之前设置ps = null ,则没有警告。

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

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

如果您有此警告,则表示您使用的是Java 7.在这种情况下,您不应自行关闭实现AutoClosable的资源。 您应该在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推荐使用我上面描述的自动关闭资源的方法,所以试试这个。

我认为,你正在使用的检查器存在问题。

将代码分解为initializationuse块。 此外,将exception抛出初始化块(或提前返回)。 这样,在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()); }; } 

将变量名称从c更改为mC。 我认为使用c作为变量名称是一个奇怪的故障。 谢谢查理