zoukankan      html  css  js  c++  java
  • Best practice to use ConcurrentMap's putIfAbsent

    http://stackoverflow.com/questions/3752194/best-practice-to-use-concurrentmaps-putifabsent

    ——————————————————————————————————————————————————

    I have been using Java's ConcurrentMap for a map that can be used from multiple threads. The putIfAbsent is a great method and is much easier to read/write than using standard map operations. I have some code that looks like this:

    ConcurrentMap<String, Set<X>> map = new ConcurrentHashMap<String, Set<X>>();    // ...    map.putIfAbsent(name, new HashSet<X>());  map.get(name).add(Y);  

    Readability wise this is great but it does require creating a new HashSet every time even if it is already in the map. I could write this:

    if (!map.containsKey(name)) {      map.putIfAbsent(name, new HashSet<X>());  }  map.get(name).add(Y);  

    With this change it loses a bit of readability but does not need to create the HashSet every time. Which is better in this case? I tend to side with the first one since it is more readable. The second would perform better and may be more correct. Maybe there is a better way to do this than either of these.

    What is the best practice for using a putIfAbsent in this manner?

    ————————————————————

    Concurrency is hard. If you are going to bother with concurrent maps instead of straightforward locking, you might as well go for it. Indeed, don't do lookups more than necessary.

    Set<X> set = map.get(name);  if (set == null) {      final Set<X> value = new HashSet<X>();      set = map.putIfAbsent(name, value);      if (set == null) {          set = value;      }  }  
    ——————————————————————————————————
    傲轩游戏网
  • 相关阅读:
    开源协议
    开发新技能
    UML 思维导图 思维脑图 xmind
    小方法
    Android Service
    JS 下载图片
    quartz任务执行完之后再执行下一轮任务
    easyui 下边有滚动条问题
    微信支付证书 系统找不到指定的文件
    Swiper 动态加载数据没有变化问题
  • 原文地址:https://www.cnblogs.com/cuizhf/p/2236141.html
Copyright © 2011-2022 走看看