Is java.sql.Connection thread safe?

JavaMultithreadingJdbcThread SafetyDbconnection

Java Problem Overview


To rephrase the question: should I avoid sharing instances of classes which implement java.sql.Connection between different threads?

Java Solutions


Solution 1 - Java

If the JDBC driver is spec-compliant, then technically yes, the object is thread-safe, but you should avoid sharing connections between threads, since the activity on the connection will mean that only one thread will be able to do anything at a time.

You should use a connection pool (like Apache Commons DBCP) to ensure that each thread gets its own connection.

Solution 2 - Java

java.sql.Connection is an interface. So, it all depends on the driver's implementation, but in general you should avoid sharing the same connection between different threads and use connection pools. Also it is also advised to have number of connections in the pool higher than number of worker threads.

Solution 3 - Java

This is rather an old thread, but for those who are looking for an answer regarding Microsoft SQL Server, here is the answer:

> SQLServerConnection is not thread safe, however multiple statements created from a single connection can be processing simultaneously in concurrent threads.

and > SQLServerConnection implements a JDBC connection to SQL Server.

From all the above, you can share statements but not Connections, and in case you need a connection in each thread, you may use a thread pool.

Read more here

Solution 4 - Java

Oracle JDBC and Multithreading docs: > Because all Oracle JDBC API methods are synchronized, if two threads try to use the connection object simultaneously, then one will be forced to wait until the other one finishes its use.

So it may be safe in Oracle case but concurrent access would suffer from bottleneck.

Solution 5 - Java

We had ArrayOutOfBoundsException on the Websphere statement cache of it's pooleddatasource, and we had to disable that cache.

We had a treatment that was blocking itself.

All of that because of current access to the connection, so the conclusion by real life practice, is that you must not do that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoris PavlovićView Question on Stackoverflow
Solution 1 - JavaskaffmanView Answer on Stackoverflow
Solution 2 - JavaAndrey AdamovichView Answer on Stackoverflow
Solution 3 - JavaHanash YaslemView Answer on Stackoverflow
Solution 4 - JavaVadzimView Answer on Stackoverflow
Solution 5 - JavaMirakView Answer on Stackoverflow