【问题标题】:Determine if 'put' operation actually executed in putIfAbsent method of ConcurrentHashMap?确定是否在 ConcurrentHashMap 的 putIfAbsent 方法中实际执行了“put”操作?
【发布时间】:2020-11-24 12:18:08
【问题描述】:

我想知道在ConcurrentHashMap的putIfAbsent方法中是否实际执行了'put'操作。

这就是我想要的:

if(map.putIfAbsent(Key,Value)){//Clearly this is wrong
  return true;
}

//other operation

return false;

【问题讨论】:

  • 您的退货单中有拼写错误。

标签: java concurrency java.util.concurrent


【解决方案1】:

Map#putIfAbsent 将在不存在关联键或键的值为 null 时返回 null。否则它将返回现有值。

V resultOfPut = map.putIfAbsent(key, value);

if (resultOfPut == null) {
    // was able to put
} else {
    // was not able to put, value already exists
}

【讨论】:

  • 您也可以将条件更改为:if (map.putIfAbsent(Key,Value) != null),以最少的工作量。 :p
  • @Mr.Polywhirl(btw 这个名字真棒)是的,非常正确,我只是定义了局部变量以使其更具描述性和清晰性(可以说不太清楚哈哈)。
  • 不错,谢谢~ 看到java doc"指定key关联的前一个值,如果key没有映射则为null。(返回null也可以表示之前的map如果实现支持 null 值,则将 null 与键关联。)"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 2017-04-29
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多