Question about atomicity in ConcurrentHashMap

Gernot Neppert mcnepp02 at googlemail.com
Thu May 23 09:11:33 PDT 2013


Am 23.05.2013 17:33, schrieb Brian Goetz:
> This is subtle.
>
> Just as everything else about Map does not make any promises about
> thread-safety or atomicity, computeIfAbsent in Map does not either.
> However, when used in a thread-confined manner, just like anything else
> about a non-thread-safe Map, it still useful and sensible and well-defined.
>
> Just as ConcurrentMap adds additional thread-safety semantics to the
> methods of Map, it adds atomicity to computeIfAbsent.  It is allowable
> for an interface like ConcurrentMap to be stronger than a superinterface
> like Map.
>
> As it turns out, the defaults in Map are carefully written so as to only
> depend on methods that are atomic in ConcurrentMap, so magically when
> inherited by a ConcurrentMap, they are atomic.
>

Thanks for your answer!
It seems we have different conceptions of "atomic".
Granted, the default implementations of the "compute..."  methods 
(inherited by ConcurrentHashMap) rely on other instance methods which 
are themselves atomic in CHM.
This will prevent corruption of the internal structure of the Map, thus 
the new operations are, in a sense, "thread-safe".

But the entire _operation_ that consists, in the case of 
"computeIfAbsent", of the following code (directly copied from the 
JavaDocs) is not what I call atomic:

if (map.get(key) == null) {
      V newValue = mappingFunction.apply(key);
      if (newValue != null)
          map.putIfAbsent(key, newValue);
  }


2 Threads accessing this might end up both calling the factory method 
which is exactly what "computeIfAbsent" was meant to prevent, right?




More information about the lambda-dev mailing list