gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:35:47 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com