I have a ServiceLocator shown below
public class ServiceLocator {
private static ServiceLocator serviceLocator = null;
InitialContext context = null;
HashMap serviceCache = null;
public ServiceLocator() throws NamingException {
context = new InitialContext();
serviceCache = new HashMap(5);
}
public synchronized static ServiceLocator getInstance()
throws NamingException {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public Object getService(String jndiName) throws NamingException {
if (!serviceCache.containsKey(jndiName)) {
serviceCache.put(jndiName, context.lookup(jndiName));
}
return serviceCache.get(jndiName);
}
}
Could anybody tell me why does we need to store JNDI name in this way ??
serviceCache.put(jndiName, context.lookup(jndiName));
Who says you need to do that? It’s just caching the results of the JNDI lookup. Under certain circumstances, JNDI lookups can be slow, so caching them may be a good idea.
I’d find out if you really need to do this, though. The JNDI lookups may be fast enough on their own. If so, then take the
serviceCacheout.