1

我已经对这个主题做了足够的研究,但还没有找到具体的答案。以下是代码片段,

private static Map<String,DataSource> dataSourceMap;

    static {
      Map<String,DataSource> jndiContextDataSourceMap = new HashMap<>();
      try {
        jndiContextDataSourceMap.put(JNDI_DEFAULT_DATASOURCE, (DataSource) new InitialContext().lookup(JNDI_DEFAULT_DATASOURCE));
      } catch (NamingException namingException) {
        logger.error("Unable to obtain default DataSource through JNDI Lookup.", namingException);
      }
      try {
        jndiContextDataSourceMap.put(JNDI_READ_REPLICA, (DataSource) new InitialContext().lookup(JNDI_READ_REPLICA));
      } catch (NamingException namingException) {
        logger.error("Unable to obtain read only DataSource through JNDI Lookup.", namingException);
      }
      dataSourceMap = Collections.unmodifiableMap(jndiContextDataSourceMap);
    }

使用相同的DataSource对象可以吗?我检查了docs,但实际上没有关于线程安全的细节。

我使用它来避免并避免为每个请求lookup创建一个新的。InitialContext

4

1 回答 1

1

是的,应该没问题。由于DataSource负责提供 a Connection,因此不使其成为线程安全的将是一个非常糟糕的主意。毕竟大多数程序同时使用多个连接。它可能没有被记录为线程安全,也没有指定它应该是线程安全的,但是任何理智的实现都是线程安全的。

于 2019-09-06T07:38:14.113 回答