1

I have done enough research on this topic, but yet to find a concrete answer for this. Following is the code snippet,

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);
    }

Is it fine to use same DataSource object? I checked the docs, but that contains really no specifics on the thread-safety.

I am using this to avoid lookup and to avoid creating a new InitialContext for every request.

Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35

1 Answers1

1

Yes, it should be alright. Since DataSource is responsible for providing a Connection, it would be a very poor idea not to make it thread-safe. Most programs use multiple connections concurrently after all. It might not be documented as thread-safe and it's not specified that it should be thread-safe, but any sane implementation is thread-safe.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • "should be alright" is different from, "it is alright" . Right? And, would be grateful if you could explain why as well codewise. – Mohamed Anees A Sep 06 '19 at 09:08
  • Well like I said, nothing stops you from writing a non-threadsafe `DataSource`, but it would be completely unusable for anything but a single threaded application. – Kayaman Sep 06 '19 at 12:05