Pools and PreparedStatements

November 5th, 2003

A few months ago, we encountered performance problems when accessing our DB. After some searching, we quickly found out that PreparedStatements actually are better than plain Statements (don't ask). But this only is the case if you can reuse the same PreparedStatement over and over again, on the same connection. Since we were using a Connection pool, the question was raised whether putting a Connection back in the pool wouldn't "erase" its PreparedStatement pool. Since we didn't find any answer to this question, we decided to take the safe way, and build our own PreparedStatementCache. Do I surprise you if I tell you that this isn't as easy as it seems? Especially if you start mixing in Threads to clean up statements and the like....

To make a long story short, the PreparedStatementCache kept causing headaches. Every now and then, we encountered closed PreparedStatements on places where they weren't meant to be. So yesterday, I weeded everything away again, replacing everything with a ConnectionPool from Oracle (instead of the single connection we were using before). The major question remained though: If we put Connections back into the pool, will their PreparedStatements be reusable?

And this morning, I googled to finally find this article. Praise the Lord. Months of headaches down the drain. I'm a happy man today.

Update: read this too. Very interesting.

Update 2: I still wasn't very happy with the solution we got, because it was very Oracle-dependent (and in fact even dependent on the version of classes12.zip you were using). Thanks to a comment from Wim, I found out that DBCP also does Statement caching. I had heard about DBCP before, and have investigated it for this, but didn't find the reference to Statement caching. Thanks Wim! However, according to Koen, c3p0 should do a better job than DBCP. And it also has the StatementCaching option, so we went for that one. Fingers crossed that it passes the real-life tests.

3 Responses to “Pools and PreparedStatements”

  1. Wim Says:
    Why didn't you use the Jakarta Commons DBCP? It has a configurable option to enable PreparedStatement pooling per connection: take a look at the parameter "poolPreparedStatements" on http://jakarta.apache.org/commons/dbcp/configuration.html
  2. SnowWolf Says:
    JDBC 3.0 solves this with out code changes. The spec reads: The JDBC 3.0 specification introduces the feature of statement pooling. This feature, which allows an application to reuse a PreparedStatement object in much the same way it can reuse a connection, is made available through a pooled connection. If you are using a JDBC 3.0 driver and a connection pool you get statement pooling.
  3. Richard Osbaldeston Says:
    tomk might be in the same position as me here; JDBC 3.0 would be a nice idea, but when (if ever) are Oracle planning to release a JDBC 3.0 version of their drivers?

Leave a Reply