我想将 computeIfPresent 和 putIfAbsent 都放到一个原子函数中
I want to have both computeIfPresent and putIfAbsent into one atomic function
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
中删除。我想要一个原子函数,如果键存在则修改值,如果不存在,它会放置 key/value.
在我当前的代码中,删除有可能发生在 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;
});
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
中删除。我想要一个原子函数,如果键存在则修改值,如果不存在,它会放置 key/value.
在我当前的代码中,删除有可能发生在 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;
});