Search code examples
javajdbcconnectionresultset

Why do I have to close JDBC resources in reverse order of use?


Why do I have to close JDBC resources in reverse order of use?

When I close a connection object, its statement object will be closed (only not using connection pool) And when I close a statement object, its resultset object will be closed (only not using cached statement)

So why a resultset object should be closed before a statement object close? (on the assumption that each exceptions are handled.) All article I've seen say all JDBC resources should be closed in reverse order of use, but do not explain why.


Solution

  • If you're using Java 7 or higher, you should use try-with-resources, which will automatically result in resources getting closed in the right order.

    In an ideal world, closing the connection will be sufficient to close the statement and the result set. However, we do not live in an ideal world. Your code is generally more complex: a statement is reused, multiple statements are executed on a single connection, etc. Closing resources as soon as they are no longer needed will make it easier to reason about your code, and prevent resource leaks, etc. Following this pattern will then automatically lead to closing resources in the reverse order they were opened, and it makes it possible for static analysis tools to detect potential resource leaks, where you don't have to verify if maybe it is a false-positive.

    In addition, in the past there have been several bugs with connection pools or drivers that did not properly close statements or result sets when a connection was returned back to the pool. Closing as soon as possible will also guard against that type of resource leak.