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

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

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

问题

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

这是我想要的:

if(map.putIfAbsent(Key,Value)){//显然这是错误的
  return true;
}

//其他操作

return false;
英文:

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

This is what I want:

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

//other operation

return false;

答案1

得分: 5

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

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

if (resultOfPut == null) {
    // 能够放置
} else {
    // 无法放置,值已存在
}
英文:

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.

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

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

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:

确定