I am using the PostgreSQL 9.1 JDBC4 driver (postgresql-9.1-902.jdbc4.jar) in a Java EE application deployed in JBoss 7.
Can I assume that javax.sql.DataSource is thread-safe so that multiple threads can concurrently call the getConnection() method on it?
javax.sql.DataSource itself is an interface, so it is a specific to the implentation if it is thread-safe or not.
For the postgres sql driver, I recommend that you read Chapter 10. Using the Driver in a Multithreaded or a Servlet Environment from the official documentation:
The PostgreSQL JDBC driver is thread safe. [...]
Typically the DataSource
implementation you get from a Java EE container will be a thread-safe object backed by a connection pool, and thread-safety (or otherwise) of the underlying JDBC connections is not really relevant. The usual pattern when you need to talk to the database is to call getConnection()
on the data source to obtain a connection object, make the necessary database calls and then close()
the connection. Under the covers this won't actually close the underlying connection, but simply return it to the connection pool for future use. Any individual connection will only be used by one thread at a time.
This is the idiom used by things like the Spring JdbcTemplate
.
If it's a 'Connection pooling implementation', then it should be thread safe.
来源:https://stackoverflow.com/questions/14872685/is-javax-sql-datasource-thread-safe