代码之家  ›  专栏  ›  技术社区  ›  Max

如何从ConcurrentHashMap<String,Set<String>>中删除用作值的集合?

  •  0
  • Max  · 技术社区  · 5 年前

    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>> key 地图是什么 String ,及 value ConcurrentHashSet .
    2. 我需要移除 set map 设置 empty .
    3. 我不能实现简单的删除 设置

    我的问题有什么绝妙的解决办法吗?

    1 回复  |  直到 5 年前
        1
  •  2
  •   user2357112    5 年前

    computeIfPresent 如果映射程序返回,则删除该项 null . 返回,而不是在单独的步骤中执行移除 如果要删除条目,请从映射器中删除。

    .add(setValue) 进入你的 computeIfAbsent 映射器,并使用 compute 而不是 add merge