March 10, 2006

A Connection Pool That Satisfies a Previous Rant

A little while ago I was talking about how many connection pools do not properly satisfy the JDBC specifications (Here.). Many home rolled connection pools do not close the resources associated with a connection before returning it to the pool.

I finally pulled my finger out and decided to have a look for a connection pool that behaved properly. Having pulled the source code for a number of connection pools (and shuddered once or twice when reading), I found a connection pool that actually works properly: Apache Commons-DBCP. The connection pool keeps track of all Statements that are created and closes them and their associated resources when the connection is returned to the pool.

As long as this pool is used, we can avoid all the JDBC clutter in our finally blocks and just close the connection when we're done.

1 comment:

Suchak Jani said...

Yes, that is the right way to do things.

This would also help point out fundamental flaws in many data access designs.

For example, there could be some badly written code where the DAO pattern is used to return a blob.

I mean, let's say there is a method in a DAO class returns a VO with a bunch of strings, ints and a blob.

A connection is given to the DAO method from a pool at the start of the method call, and it is returned back to the pool at the end of the method call.

The user of the VO then merrily uses the blob, since the connection itself and also it's resources are not closed, all works well.

The connection has just returned to the pool.

The key point here is that the blob is just a pointer to the data in the database as per this api spec:-

http://java.sun.com/j2se/1.3/docs/api/java/sql/Blob.html

The representation (mapping) in the JavaTM programming language of an SQL BLOB value. An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table. The driver implements Blob using an SQL locator(BLOB), which means that a Blob object contains a logical pointer to the SQL BLOB data rather than the data itself. A Blob object is valid for the duration of the transaction in which is was created.


I am sure that if all the resorces of the connection are closed as they should be, then the above DAO/VO code which uses the blob as-is, will fail.

Just my 2 cents