Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - Resource leak warning in eclipse

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...