tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Christopher Williams" <>
Subject Re: Memory leaks?
Date Fri, 05 Sep 2003 14:26:56 GMT
It's simple good practice to close objects that have close methods when you
no longer need them (as you do with stream objects, for example).

The spec says that ResultSet objects are closed when their Statement objects
are closed and that Statement objects are closed when their Connection
objects are closed.  I personally like to keep hold of a Connection object
for the lifetime of my application (or until it fails), because connecting
to a database is an expensive operation.  Also, if you use Connection
pooling, Connection objects can be kept open for as long as your application
server or whatever is running, so that unclosed Statements with their open
ResultSets simply sit around hogging resources (and some of the resources
that they hog, such as database cursors, are not lightweight).

This is what I do for JDBC calls:

// Assume a connection has been made
Connection conn...;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Create a PreparedStatement and use it to open a ResultSet
    // Clean up
} catch (SQLException e) {
    // Do something with the error
} finally {
    try {
        if (null != ps) {
    } catch (SQLException e) {}

This guarantees that the objects are always closed (assuming, of course,
that the close() operations succeed).  The rs.close() is, in theory,
unnecessary as the ps.close() call is supposed to close it implicitly, but
my background is in C and I always tried to free anything that I'd malloced.
It's a habit that's stuck.


View raw message