In Java, I want to do something like this:
Object r = map.get(t);
if (r == null) {
r = create(); // creating r is an expensive operation.
map.put(t, r);
}
Now that snippet of code can be executed in a multithreaded environment.
map
can be a ConcurrentHashMap.
But how do I make that logic atomic?
Please don't give me trivial solution like a 'synchronized' block. I 'd expect this problem can be solved neatly once and for all.
try
value = concurentMap.get(key);
if(value == null) {
map.putIfAbsent(key, new Value());
value = map.get(key);
}
return value;