Skip to content

Instantly share code, notes, and snippets.

@IgorBerman
Created August 18, 2014 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IgorBerman/ccf5b51f08eb5914c771 to your computer and use it in GitHub Desktop.
Save IgorBerman/ccf5b51f08eb5914c771 to your computer and use it in GitHub Desktop.
ConcurrentMap inside another ConcurrentMap with 1 only initialization
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Provider;
public class Test {
//it's safe to read from it concurrently, however we don't want that same bean will be created twice
private ConcurrentHashMap<String, ConcurrentMap<String, Object>> scopes
= new ConcurrentHashMap<String, ConcurrentMap<String, Object>>(50);
public Object get(String name, String scope, Provider<Object> objectProvider) {
ConcurrentMap<String, Object> singeltonsPerScope = getBeanCacheForTenant(scope);
if (!singeltonsPerScope.containsKey(name)) {
synchronized (singeltonsPerScope) {
if (!singeltonsPerScope.containsKey(name)) {
singeltonsPerScope.put(name, objectProvider.get());
}
}
}
return singeltonsPerScope.get(name);
}
private ConcurrentMap<String, Object> getBeanCacheForTenant(String scope) {
if (!scopes.containsKey(scope)) {
synchronized (scopes) {
if (!scopes.containsKey(scope)) {
scopes.put(scope, new ConcurrentHashMap<String, Object>(10));
}
}
}
return scopes.get(scope);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment