【发布时间】:2019-03-03 20:05:28
【问题描述】:
让我们考虑以下代码:
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>>映射,其中映射的key是String,value是ConcurrentHashSet。 - 当
set是empty时,我需要删除set,这是map的值。 - 由于竞争条件错误,我无法实现对
set的天真删除。
我的问题有什么绝妙的解决方案吗?
【问题讨论】:
-
@dnault 谢谢。
-
附带说明,由于您显然使用的是 Java 8,因此您可以对这些函数使用 lambda 表达式。
-
@Holger 是的,谢谢。我想,这段代码更明显。
标签: java concurrency race-condition java.util.concurrent concurrenthashmap