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;      }  }  
    ——————————————————————————————————
    傲轩游戏网
  • 相关阅读:
    Java 实例
    为什么很多程序员工作时都戴耳机?
    HTTP状态码大全
    Eclipse怎么切换工作空间
    maven POM.xml内的标签大全详解
    利用html5的FormData对象实现多图上传
    后台定时器注解方式
    js多定时器
    解决ios上微信无法捕获返回键按钮事件的问题
    上传文件,获取表单数据和文件流
  • 原文地址:https://www.cnblogs.com/cuizhf/p/2236141.html
Copyright © 2011-2022 走看看