一、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); } });
三、 其他
interface | non-thread-safe | thread-safe |
---|---|---|
List | ArrayList | CopyOnWriteArrayList |
Map | HashMap | ConcurrentHashMap |
Set | HashSet / TreeSet | CopyOnWriteArraySet |
Queue | ArrayDeque / LinkedList | ArrayBlockingQueue / LinkedBlockingQueue |
Deque | ArrayDeque / LinkedList | LinkedBlockingDeque |