Resource leak warning in eclipse

Reto Strub picture Reto Strub · Feb 13, 2013 · Viewed 20.1k times · Source

In Eclipse I received a warning Resource leak: 'ps' is not closed at this location that I don't understand.

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

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.

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

Is that an understanding or a java / eclipse problem?

Answer

AlexR picture AlexR · Feb 13, 2013

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.

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.