Created
August 18, 2014 11:21
-
-
Save IgorBerman/ccf5b51f08eb5914c771 to your computer and use it in GitHub Desktop.
ConcurrentMap inside another ConcurrentMap with 1 only initialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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