When Using a thread-local database connection, closure of the connection is required when the thread exists.
This I can only do if I can override the run() method of the
The normal JDBC practice is that you close the Connection
(and Statement
and ResultSet
) in the very same method block as you'd acquired it.
In code:
Connection connection = null;
try {
connection = getConnectionSomehow();
// Do stuff.
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
ignoreOrLogItButDontThrowIt(e);
}
}
}
Keeping this in mind, your question makes me think that there's something wrong in your design. Acquiring and closing those kind of expensive and external resources in the shortest scope will save the application from potential resource leaks and crashes.
If your original intent was to improve connecting performance, then you need to take a look for connection pooling. You can use for example the C3P0 API for this. Or if it's a webapplication, use the appserver's builtin connection pooling facilities in flavor of a DataSource
. Consult the appserver specific documentation for details.