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.
I think the solution is documented in concurrency in practice.
The trick is to use a Future instead of R as object in the map.
Although I dislike this answer because it looks far far too complex.
here is the code: