Mercenary
Mercenary

Reputation: 2166

Database connections in connection pool

For a code similar to this,

try{
Connection con =....
Statement stmt = ....
ResultSet set = ...
}
catch(Exception e){
...
}
finally {
con.close();
}

Given that the connection goes to a connection pool:

When con.close() is called, it goes to the connection pool and remains active. At one point of time, these connections get closed right? In that case, do we need to close result set and stmt objects as the connection will eventually get closed?

Also, can there be a situation where the stmt/result set objects might still be used and causing the connection in connection pool not getting closed?

Upvotes: 0

Views: 112

Answers (2)

Keerthivasan
Keerthivasan

Reputation: 12880

When you are using connection pooling, Connection.close() invocation would put the connection back to the pool. The Statement objects will be removed when you call Connection.close(). But, AFAIK, you have to close the ResultSet objects to clear them from server explicitly. it's a good way to always close ResultSet,Statement explicitly and not to rely on Connection.close().Adding to that, if you may opt for Spring JDBC, it will take care of managing the JDBC resources. You don't have to worry about closing connections, statements and resultsets. Adding to that, from Statement API - When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

Upvotes: 1

Puce
Puce

Reputation: 38122

It's recommended to release resources as soon as they are not needed anymore.

The easiest way is to use the new try-with-resources feature (Java SE 7).

Upvotes: 1

Related Questions