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
posted @   Mars.wang  阅读(612)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2018-05-18 java设计模式-原型(prototype)
点击右上角即可分享
微信分享提示