I’m using plain-JDBC-Database-Access in a multithreaded environment.
An exception I recently got when working with PreparedStatements (the Oracle flavour) made me aware of the fact, that they are not threadsafe.
There is, of course, always the possibility to use ThreadLocal-Variables (or synchronize access to the statement), but is there a more clever way to access a database in a multithreaded way?
Edit: To simplify the problem, I’m accessing the database read-only so parallel transactions are no concern to me.
Putting the
PreparedStatementinto aThreadLocalinto will not solve the problem – even theConnectionmust be put intoThreadLocal. But then you must make sure, that the connection is also released properly even when exceptions are thrown.And what about transactions? How do you make sure, that one transaction does not contain stuff from independent threads?
The best way would be to adopt some patterns of EJB containers – here the infrastructure takes care of the resource and transaction management and connection pooling. But retrofitting existing code into EJB or even Spring correctly is not an easy task.