Under what circumstances will this resource flow?

Eclipse 4 gives a warning saying that stmtit could not potentially be closed and cause a resource leak:

class Test {
    public void test() {
        PreparedStatement stmt = null;
        try {
            stmt = HibernateSession.instance().connection().prepareStatement("");
        } catch (final SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null)
                try {
                    stmt.close();
                } catch (final SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}

Under what circumstances will this happen?

+5
source share
4 answers

I assume the output is here: is it an Eclipse error?

+2
source

A leak is possible if an exception occurs when calling stmt.close()in a block finally.

-1
source

, finally , stmt.

, finally :

JDBCUtilities.close(stmt);

docs JDBCUtilities.close. , , . , null stmt, .

, JDBCUtilities.

-1

Java 7 try-finally:

try(stmt = HibernateSession.instance().connection().prepareStatement("")) {


}

, AutoCloseable, . ( Closeable, , ).

, , , .

Foo f = null; // don't do this, but it what you're doing
f = new Foo();

, , , .

, try/finally . .close() , ?

try { // don't do this
    stmt.close();
}
catch(SQLException exc) {

}

Eclipse, , -, . , , , Eclipse > Preferences > Compiler , . , , , . ( ).

-2

All Articles