What is JDBC Connection.isClosed () and why is Snaq DBPool not performing well?
I have the following code in Java:
if(!conn.isClosed())
{
conn.close();
}
Instead of work, I am awarded:
java.sql.SQLException: connection is already closed
My connection object is Snaq.db.CacheConnection
I checked the JavaDocs for isClosed and they stated that:
This method usually cannot be called to determine whether the connection to the database is valid or invalid. a typical client can determine that the connection is invalid if you have an exception that the operation may be in progress.
So my questions are:
1) What's good about JDBC isClosed ()? Since when do we use Java Exceptions for validation?
2) What is the correct pattern for closing the database? Should I just close and swallow exceptions?
3) Any idea why SnaqDB will close the connection? (My backend is Postgres 8.3)
a source to share
I will answer your questions with the corresponding numbers:
- I agree with you, it seems odd that only
isClosed
enforces a closed state from the best point of view, and that your code should still be prepared to catch an exception when closing the connection. I think the reason is that the connection can be closed at any time in the database, and so any status returned by the request state method, for exampleisClosed
, is initially outdated information - the state can change between checkingisClosed
and callingclose
onConnection
. - Closing calls does not affect your data and previous requests. JDBC operations run with synchronous results, so all useful execution has either succeeded or failed by the time Closed is called. (True with both autoCommit and explicit transaction boundaries.) If your application is the only user accessing the local database, perhaps showing the error to the user can help them diagnose problems. In other environments, logging exceptions and swallowing is probably the best course of action. In any case, it is safe to swallow the expression as it does not affect the state of the database.
- Looking at the source for the SnaqDB CacheConnection , the method
isClosed
delegates the underlying connection. Thus, the problem does not exist, but lies with a specific contract forisClosed()
andConnection.close()
, throwing an exception.
a source to share