ConcurrentHashMap put vs putIfAbsent [英] ConcurrentHashMap put vs putIfAbsent
问题描述
Java Google文档说, putIfAbsent
等效于
Java Docs says that, putIfAbsent
is equivalent to
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
因此,如果键存在于地图中,它不会更新其值。这是否正确?
So if the key exists in the map, it doesn't update its value. Is this correct?
如果我想根据某些条件更新键值,该怎么办?说到期时间等。
What if i want to update a keys value based on some criteria? Say expiration time etc.
这是更好的添加和更新缓存吗?
Would this be a better impl for adding and updating cache?
public void AddToCache(T key, V value)
{
V local = _cache.putifabsent(key, value);
if(local.equals(value) && local.IsExpired() == false){
return;
}
// this is for updating the cache with a new value
_cache.put(key, value);
}
推荐答案
所以它不更新一个键的值。这是正确的吗?
So it doesnt update a key's value. is this correct?
这是正确的。它会返回已经在地图中的当前值。
That is correct. It will return the current value that was already in the Map.
这将更好地添加和更新缓存吗?
would this be a better impl for adding and updating cache?
有些事情会使您的实现更好。
A couple things would make your implementation better.
/ strong>你不应该使用putIfAbsent测试它是否存在,你应该只使用它,当你想确保如果一个不存在然后 putIfAbsent
。相反,您应该使用 map.get
来测试它的存在性(或map.contains)。
1. You shouldn't use putIfAbsent to test if it exists, you should only use it when you want to ensure if one does not exist then putIfAbsent
. Instead you should use map.get
to test it's existence (or map.contains).
V local = _cache.get(key);
if (local.equals(value) && !local.IsExpired()) {
return;
}
2。替换,这是因为如果 if
可以被两个或多个线程评估为假,其中两个(或多个)线程之一将覆盖
2. Instead of put you will want to replace, this is because a race condition can occur where the if
can be evaluated as false by two or more threads in which one of the two (or more) threads will overwrite the other thread's puts.
您可以改为替换
当所有内容都完成后,像这样
When all is said and done it could look like this
public void AddToCache(T key, V value) {
for (;;) {
V local = _cache.get(key);
if(local == null){
local = _cache.putIfAbsent(key, value);
if(local == null)
return;
}
if (local.equals(value) && !local.IsExpired()) {
return;
}
if (_cache.replace(key, local, value))
return;
}
}
这篇关于ConcurrentHashMap put vs putIfAbsent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!