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
389 views
in Technique[技术] by (71.8m points)

java - Possible resource leak when reusing PreparedStatement?

Suppose you have the following code:

    Connection connection = null;
    PreparedStatement ps = null;

    try {
        Connection = connectionFactory.getConnection();

        ps = statement.prepareStamement(someQuery);
        // execute and read and stuff

        // now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
        ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
    } catch (a lot of exceptions) {
        // process exceptions
    } finally {

        // close the resources (using util class with null-checks and everything)
        SomeUtilClass.close(ps);
        SomeUtilClass.close(connection);
    }

Is reusing the ps variable a potential leak?

And if so, I would hate to declare multiple of such prepared statements (ps1, ps2, ps3, etc). How should I refactor this?

Thoughts anyone?

EDIT

Receiving several answers stating that this doesn't matter. I would like to point out that I'm experiencing open cursors that stay open a little bit too long, and was wondering if this pattern might have something to do with it.

My thoughts were:

The first statement gets dereferenced and GC'ed, so how does the first PreparedStatement get closed (Database-wise) in this example?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This would not necessarily create a leak in a classic, "permanent", sense. The garbage collector will get to the first instance of the prepared statement eventually, and call its finalizer.

However, this is not a good practice to let the garbage collector deal with freeing potentially critical resources, such as DB handles: you should call the close method before reusing the prepared statement variable, or not reuse the variable at all.

try {
    Connection = connectionFactory.getConnection();

    ps = statement.prepareStamement(someQuery);
    // execute and read and stuff

    // now you want to use the ps again, since you don't want ps1, ps2, ps3, etc.
    // v v v v v v v v v v v
    SomeUtilClass.close(ps);
    // ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
    ps = statement.prepareStatement(someOtherQuery); // DOES THIS FORM A POTENTIAL LEAK?
} catch (a lot of exceptions) {
    // process exceptions
} finally {

    // close the resources (using util class with null-checks and everything)
    SomeUtilClass.close(ps);
    SomeUtilClass.close(connection);
}

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

...