作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
让我们考虑以下代码:
ConcurrentHashMap<String, Set<String>> map = new ConcurrentHashMap<>();
// Add element: {mapKey, setValue}
map.computeIfAbsent(mapKey, new Function<String, Set<String>>() {
@Override
public Set<String> apply(String mapK) {
return ConcurrentHashMap.newKeySet();
}
}).add(setValue);
// Remove element: {mapKey, setValue}
Set<String> updatedSet = map.computeIfPresent(mapKey, new BiFunction<String, Set<String>, Set<String>>() {
@Override
public Set<String> apply(String mapK, Set<String> old) {
old.remove(setValue);
return old;
}
});
// I need remove mapKey, but I cannod do this like this, because of race condition bug
if (updatedSet.isEmpty()) {
map.remove(mapKey);
}
所以,我们可以看到:
ConcurrentHashMap<String, Set<String>>
map ,哪里key
map 是String
,和value
是 ConcurrentHashSet
.set
,其值为 map
,当 set
是 empty
.set
,因为竞争条件错误。有什么好的办法可以解决我的问题吗?
最佳答案
如果映射器返回 null
,
computeIfPresent
将删除该条目。如果您想删除条目,请从映射器返回 null
,而不是在单独的步骤中执行删除。
(另外,您应该将 .add(setValue)
折叠到您的 computeIfAbsent
映射器中,并使用 compute
而不是 computeIfAbsent
,因为您现在没有执行任何操作来保护 add
调用。使用 merge
也是一种选择。)
关于java - 如何从 ConcurrentHashMap<String, Set<String>> 中删除用作值的 Set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54973188/
我是一名优秀的程序员,十分优秀!