gpt4 book ai didi

java - 如何从 ConcurrentHashMap> 中删除用作值的 Set?

转载 作者:行者123 更新时间:2023-12-02 01:37:46 26 4
gpt4 key购买 nike

让我们考虑以下代码:

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);
}

所以,我们可以看到:

  1. 我们有ConcurrentHashMap<String, Set<String>> map ,哪里key map 是String ,和valueConcurrentHashSet .
  2. 我需要删除set ,其值为 map ,当 setempty .
  3. 我无法简单地删除 set ,因为竞争条件错误。

有什么好的办法可以解决我的问题吗?

最佳答案

如果映射器返回 null

computeIfPresent 将删除该条目。如果您想删除条目,请从映射器返回 null,而不是在单独的步骤中执行删除。

(另外,您应该将 .add(setValue) 折叠到您的 computeIfAbsent 映射器中,并使用 compute 而不是 computeIfAbsent,因为您现在没有执行任何操作来保护 add 调用。使用 merge 也是一种选择。)

关于java - 如何从 ConcurrentHashMap<String, Set<String>> 中删除用作值的 Set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54973188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com