Should this method be synchronized? I guess I don't understand how (and when) context switches can occur, so I don't know if it's possible for more than one thread to get into the if block inside my method.
public class ServiceLocator {
private static final Map<Class, Object> applicationServices =
new HashMap<Class, Object>();
/**
* Locates an application scoped service. The service is lazy loaded and
* will be cached permanently.
*
* @param type The type of service to locate.
* @return An application scoped service of the specified type.
*/
@SuppressWarnings({"unchecked"})
public synchronized static <T> T getApplicationService(Class<T> type) {
if(!applicationServices.containsKey(type)) {
// If this method is NOT synchronized, is it possible for more than
// one thread to get into this if block?
T newService = ServiceLoader.create(type);
applicationServices.put(type, newService);
return newService;
}
return (T) applicationServices.get(type);
}
}