java - Postgres JDBC 驱动程序 `org.postgresql.ds.PGSimpleDataSource` 是线程安全的吗?

标签 java multithreading postgresql jdbc thread-safety

JDBC driver for Postgres , 是 PGSimpleDataSource线程安全?

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

我试图避免 (a) 在 Connection 上进行多线程调用和 (b) 使用连接池,如 discussed in the doc .我想为每个 servlet 线程创建一个单独的 Connection

最佳答案

我假设您不会在多个线程上更改数据源配置,因为那样它就不是线程安全的。您可以在 https://github.com/pgjdbc/pgjdbc 上自行检查源代码,getConnection的具体代码在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;
    }
}

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

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

关于java - Postgres JDBC 驱动程序 `org.postgresql.ds.PGSimpleDataSource` 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094627/

相关文章:

java - 如何创建自适应 Android 应用

java - Spring @Controller 调用 @Async 方法,然后在返回的 Future 上调用 get()...代码味道?

postgresql - 错误 : row is too big: size 8168, 最大尺寸 8164

c - 将整数作为二进制发送时出现 PostgreSQL libpq "Integer out of range"错误

java - 如何从 JPanel 类访问 JFrame 组件?

java - 如何在 Selenium WebDriver 中启用验证按钮?

java - 抽象父类(super class)中的 protected 字段是否应该在子类中使用 super 或 this 来访问?

java - android 在另一个重复任务完成时运行重复任务

java - RxJava2多线程或者出现问题

postgresql - 一个好的 PgPool II 配置