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.