13

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?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
  • 1
    The JCIP book addresses this, I quoted the relevant passage in an answer to a related question, see https://stackoverflow.com/a/31588609/217324 – Nathan Hughes Oct 17 '22 at 14:43

3 Answers3

11

javax.sql.DataSource itself is an interface, so it is a specific to the implentation if it is thread-safe or not.

For the PostgresSQL driver, the official documentation changed over time. While older documentation (snapshot) wrote it is, the current documentation writing the opposite, stating that is not thread-safe.

Dag
  • 10,079
  • 8
  • 51
  • 74
11

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
1

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

D_S_toowhite
  • 643
  • 5
  • 17