Postgres JDBC 驱动程序“org.postgresql.ds.PGSimpleDataSource”线程安全吗?

Bas*_*que 1 java postgresql multithreading jdbc thread-safety

Postgres 的 JDBC 驱动程序中,PGSimpleDataSource线程安全吗?

也就是说,如果我使用该类的缓存单例实例,我可以将其传递给多个线程吗?getConnection每个线程可能在同一时刻调用。该文档没有提及线程安全。

我试图避免 (a) 对 a 进行多线程调用Connection和 (b) 使用连接池,如doc 中所述。我想要Connection每个 servlet 线程都有一个单独的线程。

Mar*_*eel 5

我假设您不会在多个线程上更改数据源配置,因为那样它就不是线程安全的。大家可以自行查看源码,https ://github.com/pgjdbc/pgjdbc,具体代码getConnectionBaseDataSource

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

换句话说,它是一个薄薄的包装纸DriverManagerDriverManager本身是线程安全的,那么是否org.postgresql.Driver线程安全就成了一个问题。我没有时间尝试验证这一点,但我们只能说,如果这不是线程安全的,那将是非常令人惊讶的(否则世界范围的应用程序将因各种奇怪的竞争条件等而失败)。

附带说明:PGSimpleDataSource不提供连接池,您可能需要考虑这是否适合您的用例。