判断 putIfAbsent 是否修改了 ConcurrentHashMap 的正确方法是什么?

What is the correct way to tell whether putIfAbsent modified a ConcurrentHashMap?

我正在使用 putIfAbsent 将值添加到 ConcurrentHashMap,如果它们不作为原子操作存在的话。

这一切看起来都很好,但我真的可以判断是否真的添加了一个新对象。

我的最佳想法是检查 putIfAbsent 的 return 值是否为 null,只要我们从不将 null 值放入映射(ConcurrentHashMap 不允许),它看起来应该可以工作无论如何)但我想知道我是否错过了什么。或者这是正确的方法吗?

在这种情况下使用 CHM 的最佳方式是这样的:

Object o = concurrentMap.get(key);

if(o == null){
   Object ret = concurrentMap.putIfAbsent(key, value);
   if(ret == null){
      o = ret;
   }
}
return o;

get 调用是 non-blocking,因此您想尽可能多地利用 non-blocking 调用。如果调用了很多,连续调用 putIfAbsent 会降低性能。