Re: thread safe JDBC code



"Steve" <javacc2@xxxxxxxxx> wrote in message
news:4cf5dc4a-e127-42f0-96be-b95c437512f3@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
How to guarantee the JDBC code is thread safe? Should we put
synchronize block in JDBC methods that performs update/delete
operations?

please advice. thanks.

Here are some articles (despite the titles, not MySQL specific) that discuss
the general problem:

http://www.mysql.com/news-and-events/newsletter/2003-04/a0000000154.html

Key phrases: "The answer to this problem is to realize that a unit of work
is scoped by a java.sql.Connection instance. In fact, even transaction
control is scoped to a java.sql.Connection, via Connection.setAutoCommit(),
Connection.commit() and Connection.rollback(). Therefore, let only one
thread at a time use a Connection instance to do its unit of work. There are
multiple strategies for doing this, from giving each thread its own
Connection instance, or sharing Connection instances via a Connection pool."

Note: one can also use ThreadLocal.

http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html

Has code example. Recall that local variables are unique to a thread, unlike
instance and class variables. Therefore, if thread A gets a connection
locally then Threads B and C won't be accessing it.

AHS


.