Is java.sql.Connection thread safe? Is java.sql.Connection thread safe? multithreading multithreading

Is java.sql.Connection thread safe?


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.


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.


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