Re: Will calling "close()" on a "java.sql.Connection" really close
associated resources?
david.karr wrote:
In billions of lines of code using JDBC connections, I constantly see
Clearly you exaggerate.
finally clauses that first close a ResultSet, then a Statement, and
then a Connection (if any of them are non-null). The thing is, the
javadoc for the "close()" method says this:
"Releases this Connection object's database and JDBC resources
immediately instead of waiting for them to be automatically released.
"
That implies to me that manually closing the ResultSet and Statement
just before closing the Connection is a waste of perfectly good
bytecode.
If I'm understanding this correctly, is there any situation where it's
still a good idea to manually close the resources when you're about to
close the connection?
Arne Vajh?j wrote:
JDBC spec says:
[elided]
So they will be closed.
But actually I think it is good to do it explicit. Because
it makes it obvious that they are being closed also to those
that have not read the JDBC spec.
Readable code is better than short code.
It is also common to wish to close a statement but not the connection.
Likewise result sets but not statements. By maintaining the discipline of
closing statements and result sets explicitly, one avoids some risks:
- Modifying code that depended on closing the connection so that it is no
longer "about to close", and thus leaving the statements / result sets open
longer than intended.
- Deciding that one should just leave statements / result sets open as long as
the connection is, then attempting to scale for more clients or more
throughput but encountering artificial scarcity that impedes scalability.
- Having to spend thought and time to decide if one should tidy up the
statements and result sets, and then all over again when one refactors.
- The risks mentioned by Arne and Lothar.
- As above, but when someone else maintains the code.
--
Lew