1
votes

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.

1
@Gilberto Actually, that doc you linked only talks about (a) executing a query on a Connection, and (b) using a connection pool. My Question is about getConnection on PGSimpleDataSource, a separate subject. I asked because I am distinctly trying to avoid both (a) and (b).Basil Bourque
I was trying to show this: The PostgreSQL™ JDBC driver is thread safe. Consequently, if your application uses multiple threads then you do not have to worry about complex algorithms to ensure that only one thread uses the database at a time.Gilberto
@Gilberto Your quote is taken out of context, and does not Answer my question. As I said above, that quoted doc addresses other multithreading issues, not the issue I asked.Basil Bourque

1 Answers

4
votes

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.