Java ConcurrentHashMap原子获取(如果存在)

cdm*_*hai 4 java concurrenthashmap

如何在并发哈希映射上执行安全获取操作?(与putIfAbsent相同)

不好的例子,不是非常线程安全(检查然后行为情况):

ConcurrentMap<String, SomeObject> concMap = new ...

//... many putIfAbsent and remove operations

public boolean setOption(String id, Object option){
   SomeObject obj = concMap.get(id);

   if (obj != null){
      //what if this key has been removed from the map?
      obj.setOption(option);
      return true;
   }

   // in the meantime a putIfAbsent may have been called on the map and then this
   //setOption call is no longer correct

   return false;
}
Run Code Online (Sandbox Code Playgroud)

另一个糟糕的例子是:

   public boolean setOption(String id, Object option){
       if (concMap.contains(id)){
           concMap.get(id).setOption(option);
           return true;
       }
       return false;
    }
Run Code Online (Sandbox Code Playgroud)

这里需要的是不要通过同步来阻止添加,删除和获取操作.

谢谢

Chr*_*rau 6

a上的get()方法ConcurrentHashMap是原子的.由于该映射不允许空值,因此get()实现"get if present":如果结果为null,则该键不存在.

  • 如果你需要这种级别的排他性,你需要像地图本身一样锁定一个中心对象,尽管你会失去使用ConcurrentMap的许多好处. (2认同)
  • null测试与另一个线程中可能的`putIfAbsent`之间没有发生过 - 之前的关系.那么,在`get`和`null`测试之间放置一个值的另一个线程与你的`setOption`之后返回`false`的另一个线程之间的区别是什么? (2认同)