[英]Do I need to synchronize ConcurrentMap when adding key only if needed?
我有一個ConcurrentMap <String,SomeObject>對象。 我想編寫一個方法,如果它存在則返回SomeObject值,或者創建一個新的SomeObject,將它放在Map中,如果它不存在則返回它。
理想情況下,我可以使用ConcurrentMap的putIfAbsent(key, new SomeObject(key))
,但這意味着我每次都創建一個新的SomeObject(key),這看起來非常浪費。
所以我使用了以下代碼,但我不確定這是處理這個問題的最佳方法:
public SomeValue getSomevalue(String key){
SomeValue result = concurrentMap.get(key);
if (result != null)
return result;
synchronized(concurrentMap){
SomeValue result = concurrentMap.get(key);
if (result == null){
result = new SomeValue(key);
concurrentMap.put(key, result);
}
return result;
}
}
理想情況下,我可以使用ConcurrentMap的putIfAbsent(key,new SomeObject(key)),但這意味着我每次都創建一個新的SomeObject(key),這看起來非常浪費。
然后使用computeIfAbsent
:
concurrentMap.computeIfAbsent(key, SomeObject::new);
使用與ConcurrentMap synchronized
不會阻止其他線程在synchronized
塊的中間對地圖執行操作。 ConcurrentMap不承諾使用map的監視器進行同步,並且ConcurrentHashMap和ConcurrentSkipListMap都不會在map對象上同步。
請注意,ConcurrentMap接口不保證該值僅計算一次,或者如果該鍵已存在則不會計算該值。 ConcurrentHashMap產生了這些承諾,但ConcurrentSkipListMap沒有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.