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.
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.