Reputation: 338785
In the JDBC driver for Postgres, is PGSimpleDataSource
thread-safe?
That is, if I use a cached singleton instance of that class, can I pass it out to multiple threads? Each thread may be calling getConnection
at the same moment. The documentation makes no mention of thread-safety.
I am trying to avoid both (a) making multi-threaded calls on a Connection
and (b) using a connection pool, as discussed in the doc. I want a separate Connection
for each servlet thread.
Upvotes: 1
Views: 4983
Reputation: 109015
I'm assuming you won't be changing the data source configuration on multiple threads, because then it isn't thread-safe. You can inspect the source code yourself, on https://github.com/pgjdbc/pgjdbc, the specific code for getConnection
is in BaseDataSource
:
public Connection getConnection(String user, String password) throws SQLException {
try {
Connection con = DriverManager.getConnection(getUrl(), user, password);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Created a {0} for {1} at {2}", new Object[]{getDescription(), user, getUrl()});
}
return con;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Failed to create a {0} for {1} at {2}: {3}",
new Object[]{getDescription(), user, getUrl(), e});
throw e;
}
}
In other words, it is a thin wrapper around DriverManager
. DriverManager
itself is thread-safe, so then it becomes a question if org.postgresql.Driver
is thread-safe. I don't have time to try to verify that, but lets just say it would be really surprising if that wasn't thread-safe (and otherwise world-wide applications would fail with all kinds of strange race-conditions, etc).
As a side note: PGSimpleDataSource
does not provide connection pooling, you might want to consider whether that is right for your use case.
Upvotes: 5