Java ConcurrentHashMap 原子获取如果存在

标签 java concurrenthashmap

如何在并发 HashMap 上执行安全获取操作? (与 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;
}

另一个不好的例子是:

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

这里可取的事情是不要通过同步添加、删除和获取操作来成为瓶颈。

谢谢

最佳答案

ConcurrentHashMap 上的get() 方法是原子的。由于该映射不允许空值,get() 实现“get if present”:如果结果为 null,则 key 不存在。

关于Java ConcurrentHashMap 原子获取如果存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353835/

相关文章:

java - 如果线程不更改映射结构,我应该使用 ConcurrentHashMap 还是 HashMap?

java - 如果我使用非最终的 ConcurrentHashMap 会发生什么

java - Objective-C,如何将这个Java语句转换成Objective-C代码?

java - 密码学:为什么我的加密初始化 vector 只影响前 16 个字节?

java - 黑莓智能卷尺?

Java 并发 hashmap 缺失值

java - ConcurrentHashMap 中的死锁

java - Hibernate - 检索所有表信息 - 列名、索引、长度并填充为表

java - LWJGL绘图时如何选择图像的区域?

java - 有没有比 ConcurrentHashMap 性能更好的并发映射?