确定在ConcurrentHashMap的putIfAbsent方法中是否实际执行了’put’操作?

huangapple go评论111阅读模式
英文:

Determine if 'put' operation actually executed in putIfAbsent method of ConcurrentHashMap?

问题

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

这是我想要的:

  1. if(map.putIfAbsent(Key,Value)){//显然这是错误的
  2. return true;
  3. }
  4. //其他操作
  5. return false;
英文:

I want to know whether 'put' operation actually executed in putIfAbsent method of ConcurrentHashMap.

This is what I want:

  1. if(map.putIfAbsent(Key,Value)){//Clearly this is wrong
  2. return true;
  3. }
  4. //other operation
  5. return false;

答案1

得分: 5

Map#putIfAbsent 如果没有关联的键存在或键的值为null,则会返回null。否则,它将返回现有的值。

  1. V resultOfPut = map.putIfAbsent(key, value);
  2. if (resultOfPut == null) {
  3. // 能够放置
  4. } else {
  5. // 无法放置,值已存在
  6. }
英文:

Map#putIfAbsent will return null if no associated key exists or the value for the key is null. Otherwise it will return the existing value.

  1. V resultOfPut = map.putIfAbsent(key, value);
  2. if (resultOfPut == null) {
  3. // was able to put
  4. } else {
  5. // was not able to put, value already exists
  6. }

huangapple
  • 本文由 发表于 2020年8月4日 19:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63246251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定