You can apply with lazy initialization with in synchronize block.
private static volatile ConcurrentHashMap<KEY, VALUE> cache = null;
public static ConcurrentHashMap<KEY, VALUE> getCacheInstance() {
if (cache == null) {
synchronized(cache) {
if (cache == null) {
cache = new ConcurrentHashMap<>();
}
}
}
return cache ;
}
public static put(ConcurrentHashMap<KEY, VALUE> cache) {
VALUE ret = cache.get(KEY);
if (ret == null) {...
}
}
In Java 8 implement local thread-safe cache is very easy.
private static final ConcurrentMap<KEY, VALUE> cache =
new ConcurrentHashMap();
public Object get(String KEY) {
return cache.computeIfAbsent(KEY, k - > createObject(k));
}
You can implement it in Java 7 with double checking thread safety.
public Object get(String KEY) {
if (!cache.containsKey(KEY)) {
synchronized (cache) {
if (!cache.containsKey(KEY)) {
cache.put(KEY, createObject(KEY));
}
}
}
return cache.get(KEY);
}
https://developer-should-know.com/post/116472734172/local-thread-safe-cache-with-java