• java中线程安全的集合


    一、CopyOnWriteArrayList

    迭代的同时进行修改会发生ConcurrentModificationException异常,推荐使用CopyOnWriteArrayList

    List<RtuTagAct> rtuTagActList = entry.getValue();
    for (RtuTagAct rtuTagAct:rtuTagActList) {
         if (rtuTagAct.getTagKey().equals(pushKey)) {
             rtuTagActList.remove(rtuTagAct);
                    }
                }

    下面是修改后的实现

    List<RtuTagAct> rtuTagActList0 = entry.getValue();
    List<RtuTagAct> rtuTagActList = new CopyOnWriteArrayList<>(rtuTagActList0);
    for (RtuTagAct rtuTagAct:rtuTagActList) {
        if (rtuTagAct.getTagKey().equals(pushKey)) {
            rtuTagActList.remove(rtuTagAct);
                    }
                }

    二、ConcurrentHashMap

    并发时修改Map,推荐使用ConcurrentHashMap,不然可能发生不可预料的后果

    比如如下实现,算出的数据根本就是错误的

    Map<String, Double> result = new HashMap<>();
    atIdList.forEach(meterId -> {
                Double now = rtValueMap.get(meterId); 
                Double node = hiveRTValueMap.get(meterId);
                double todayValue = ArithUtils.sub(now, node);
                 result.put(meterId, todayValue);  
                }
            });

    采用如下修改后的代码,果然就没问题了

    Map<String, Double> result = new ConcurrentHashMap<>();
    atIdList.forEach(meterId -> {
                Double now = rtValueMap.get(meterId); 
                Double node = hiveRTValueMap.get(meterId);
                double todayValue = ArithUtils.sub(now, node);
                 result.put(meterId, todayValue);  
                }
            });

    三、 其他

    interfacenon-thread-safethread-safe
    List ArrayList CopyOnWriteArrayList
    Map HashMap ConcurrentHashMap
    Set HashSet / TreeSet CopyOnWriteArraySet
    Queue ArrayDeque / LinkedList ArrayBlockingQueue / LinkedBlockingQueue
    Deque ArrayDeque / LinkedList LinkedBlockingDeque
  • 相关阅读:
    python 登陆接口
    FTP 的搭建过程和遇到的问题
    ELK 的好文章连接
    logstash 配置文件实例
    使用 screen 管理你的远程会话
    Conda常用命令整理
    python 增加矩阵行列和维数
    26个你不知道的Python技巧
    python单下划线、双下划线、头尾双下划线说明:
    python 类方法的互相调用及self的含义
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/14781592.html
Copyright © 2020-2023  润新知