java-我想将computeIfPresent和putIfAbsent都集成到一个原子函数中
作者:互联网
workObjectMap.computeIfPresent(key, (k,v) -> {
v.memberIdSet.addAll(memberIdSet);
v.memberPositionSet.addAll(memberPositionSet);
return v;
});
// If it.remove() in run() is called at this point,
// there is a risk of the same work being done twice
workObjectMap.putIfAbsent(key, new WorkObjectValue(memberIdSet, memberPositionSet));
我有上面的代码.在一个单独的线程中,我可能正在从workObjectMap中删除.我想要一个原子函数,如果键存在,该函数会修改值,如果不存在,它将放入键/值.
在我当前的代码中,有一次删除可能会在computeIfPresent和putIfAbsent之间发生,以便将已经添加到地图的同一项目再次添加.
如何在这两个方法调用之间阻止任何删除? (computeIfPresent和putIfAbsent)
解决方法:
workObjectMap.compute(key, (k,v) -> {
if (v == null) return new WorkObjectValue(memberIdSet, memberPositionSet);
v.memberIdSet.addAll(memberIdSet);
v.memberPositionSet.addAll(memberPositionSet);
return v;
});
注意the ConcurrentHashMap
Javadoc explicitly states这是原子的.
标签:concurrenthashmap,java-8,concurrency,atomicity,java 来源: https://codeday.me/bug/20191025/1925990.html