is javax.sql.DataSource thread safe?

蹲街弑〆低调 提交于 2019-11-27 03:29:45

问题


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?


回答1:


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. [...]




回答2:


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.




回答3:


If it's a 'Connection pooling implementation', then it should be thread safe.



来源:https://stackoverflow.com/questions/14872685/is-javax-sql-datasource-thread-safe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!