javajava.util.concurrentconcurrent-programming

Snippet for concurrentHashMap to retrieve object or create it if absent (as atomic operation)


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.


Solution

  • try

        value = concurentMap.get(key);
        if(value == null) {
            map.putIfAbsent(key, new Value());
            value = map.get(key);
        }
        return value;