如何避免ConcurrentModificationException 异常

并发修改异常ConcurrentModificationException详解 目录 一、简介 二、异常原因分析 三、异常原因追踪 五、如何避免并发修改异常? 六、总结 一、简介 在多线程编程中,相信很多小伙伴都遇到过并发修改异常ConcurrentModificationException,本篇文章我们就来讲解并发修改异常的现象以及分析一下它是如何产生的。 异常产生原因:并发修改异常指的是在并发环境下,当方法检测到对象的并发修改,但不允许这种修改时,抛出该异常。 下面看一个示例: public class TestConcurrentModifyException 阅读详情
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a  ConcurrentModificationException .

This situation can come in case of multithreaded as well as single threaded environment.

Lets explore this scenario with the following example:

import java.util.*;
 
public class IteratorExample {
 
    public static void main(String args[]){
        List<String> myList = new ArrayList<String>();
 
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
 
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")) myList.remove(value);
        }
 
        Map<String,String> myMap = new HashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "2");
        myMap.put("3", "3");
 
        Iterator<String> it1 = myMap.keySet().iterator();
        while(it1.hasNext()){
            String key = it1.next();
            System.out.println("Map Value:"+myMap.get(key));
            if(key.equals("2")){
                myMap.put("1","4");
                //myMap.put("4", "4");
            }
        }
 
    }
}

Output is:
List Value:1
List Value:2
List Value:3
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at com.journaldev.java.IteratorExample.main(IteratorExample.java:27)

From the output stack trace, its clear that the exception is coming when we call iterator next() function. If you are wondering how Iterator checks for the modification, its implementation is present in AbstractList class where an int variable modCount is defined that provides the number of times list size has been changed. This value is used in every next() call to check for any modifications in a function checkForComodification().

Now comment the list part and run the program again.

Output will be:

Map Value:3
Map Value:2
Map Value:4

Since we are updating the existing key value in the myMap, its size has not been changed and we are not getting ConcurrentModificationException. Note that the output may differ in your system because HashMap keyset is not ordered like list. If you will uncomment the statement where I am adding a new key-value in the HashMap, it will cause ConcurrentModificationException.

To Avoid ConcurrentModificationException in multi-threaded environment:

1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

To Avoid ConcurrentModificationException in single-threaded environment:

You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list.

Let us run an example using Concurrent Collection classes:

package com.journaldev.java;
 
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
 
public class ThreadSafeIteratorExample {
 
    public static void main(String[] args) {
 
        List<String> myList = new CopyOnWriteArrayList<String>();
 
        myList.add("1");
        myList.add("2");
        myList.add("3");
        myList.add("4");
        myList.add("5");
 
        Iterator<String> it = myList.iterator();
        while(it.hasNext()){
            String value = it.next();
            System.out.println("List Value:"+value);
            if(value.equals("3")){
                myList.remove("4");
                myList.add("6");
                myList.add("7");
            }
        }
        System.out.println("List Size:"+myList.size());
 
        Map<String,String> myMap = 
             new ConcurrentHashMap<String,String>();
        myMap.put("1", "1");
        myMap.put("2", "2");
        myMap.put("3", "3");
 
        Iterator<String> it1 = myMap.keySet().iterator();
        while(it1.hasNext()){
            String key = it1.next();
            System.out.println("Map Value:"+myMap.get(key));
            if(key.equals("1")){
                myMap.remove("3");
                myMap.put("4", "4");
                myMap.put("5", "5");
            }
        }
 
        System.out.println("Map Size:"+myMap.size());
    }
 
}
Output is:
List Value:1
List Value:2
List Value:3
List Value:4
List Value:5
List Size:6
Map Value:1
Map Value:null
Map Value:4
Map Value:2
Map Size:4

From the above example its clear that:

1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException.

2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list.

3. In case of ConcurrentHashMap, the behavior is not always the same.

For condition:

if(key.equals("1")){
    myMap.remove("3");

Output is:
Map Value:1
Map Value:null
Map Value:4
Map Value:2
Map Size:4

It is taking the new object added with key “4? but not the next added object with key “5?.

Now if I change the condition to

if(key.equals("3")){
    myMap.remove("2");
Output is:
Map Value:1
Map Value:3
Map Value:null
Map Size:4

In this case its not considering the new added objects.

So if you are using ConcurrentHashMap then avoid adding new objects as it can be processed depending on the keyset. Note that the same program can print different values in your system because HashMap keyset is not in any order.

Extra Toppings:

for(int i = 0; i<myList.size(); i++){
    System.out.println(myList.get(i));
    if(myList.get(i).equals("3")){
        myList.remove(i);
        i--;
        myList.add("6");
    }
}

If you are working on single-threaded environment and want your code to take care of the extra added objects in the list then you can do so using following code and avoiding iterator.

Note that I am decreasing the counter because I am removing the same object, if you have to remove the next or further far object then you don’t need to decrease the counter.

Try it yourself.

Reference :  http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html

http://www.oschina.net/code/snippet_12_4199

高效静音黑科技 —— 单相直流无刷电机驱动器 然而,传统的BLDC电机驱动通常依赖于三相架构,电路复杂,成本高昂,且在低功率应用中显得有些“大材小用”。单相直流无刷电机驱动器作为一项高效、静音、经济的技术,正逐渐改变着各个领域的电机驱动方式。其精巧的控制策略、显著的优势以及广阔的应用前景,都预示着这项技术将在未来扮演越来越重要的角色。它相较于传统的三相驱动,显著简化了电路结构,降低了成本,尤其适用于低功率、对静音要求极高的应用场景。通过这些模块的协同工作,单相直流无刷电机驱动器能够实现对电机速度、扭矩的精确控制,并最大程度地降低噪声和振动。 阅读详情

相关推荐

【深度学习】肺结节分割项目实战二:分割肺实质

在后续训练模型的时候如果直接使用原始的肺部CT图像,其中的非肺区域会对训练造成干扰,因此我们需要提取分割肺实质。这一部分参考了kaggle上的教程。 从这张CT图像中可以看出扫描器以外的部分为黑色,背景和肺内部颜色较深,非肺组织和骨头颜色较浅。我们的目的是将肺部分割出来。由于肺部区域和其他部分对比明显,我们可以设置一个合适的阈值对图像中的区域进行隔离。 import argparse import os import numpy as np from medpy.filter.smoothing imp

weixin_42182906的博客 7242

如何避免 ConcurrentModificationException 异常

在实际生产过程中,碰到了一个概念中的异常,ConcurrentModificationException。 这个异常主要出现在集合的遍历中,对集合进行了add或者remove的操作; 以ArrayList为例子,当在forEach的时候,对list本身进行add或者remove的操作,查看ArrayList的源码,相当于是移动了指针;点击查看 以HashMap为例,集合的修改有一个modCount...

张小挑的博客 1919

WSL 相关命令时遇到了 “无法从raw.githubusercontent.com提取分发列表、操作超时

核心问题:国内网络屏蔽raw.githubusercontent.com,导致WSL无法获取发行版列表;最优方案:优先用方案1(手动指定发行版安装),无需改配置,1分钟搞定;永久修复:用方案2(修改hosts),适合需要管理多个WSL发行版的场景;兜底方案:用方案3(手动下载安装包),适配所有网络环境。按以上步骤操作后,你不仅能正常安装WSL,等命令也能正常执行,后续可正常使用WSL搭配Docker Desktop(如切换WSL 2后端),无需再担心网络超时问题。

weixin_39766667的博客 2146

如何避免ConcurrentModificationException

ConcurrentModificationException出现原因: 1.在Java集合类中,当我们在使用iterator遍历集合对象时,当集合被改变且在使用迭代器遍历集合的时候,迭代器的next()方法将抛出ConcurrentModificationException异常。 2.如果subList()生成一个新的List对象,那么当修改原始List对象的结构时,则将抛出ConcurrentModificationException import java.util.ArrayList; import

weixin_43664019的博客 585

提升仿真效率:Synopsys VCS高级编译选项优化技巧(2023最新版)

本文深入探讨了Synopsys VCS 2023版本中的高级编译选项优化技巧,帮助工程师提升仿真效率。通过并行编译、智能代码分析、精准覆盖率采样等策略,结合真实案例展示如何显著缩短仿真周期并优化资源使用,适用于数字芯片验证和大型SoC设计。

weixin_30338481的博客 114

【CV论文精读】【协同感知综述】Collaborative Perception for Autonomous Driving :Current Status and Future Trend

感知是自动驾驶系统的关键模块之一,近年来取得了很大进展。然而,单个车辆的有限能力导致感知性能提高的瓶颈。为了突破个体感知的局限,协作感知被提出,它使车辆能够共享信息来感知视线和视野之外的环境。本文综述了有前途的协作感知技术的相关工作,包括介绍了基本概念,概括了协作模式,总结了协作感知的关键要素和应用。最后,我们讨论了这一研究领域面临的挑战和问题,并给出了一些潜在的进一步方向。

weixin_44184852的博客 4690

4.ConcurrentModifyException的产生原因及如何避免

4.ConcurrentModifyException的产生原因及如何避免目录1 关于ConcurrentModificationException2 单线程触发场景举例  2.1 单线程触发举例  2.2 解决单线程环境的ConcurrentModificationException异常  2.3 ArrayList集合改为CopyOnWriteArrayLis  2.4 通过迭代器遍历删除  ...

大屎蛋教程网 8007

VisionPro九点标定实战:从相机拍照到机器人精准抓取的完整流程

本文详细介绍了VisionPro九点标定技术在工业自动化中的应用,从相机拍照到机器人精准抓取的完整流程。通过硬件配置、标定步骤和实战技巧的解析,帮助工程师实现高精度视觉引导系统,提升生产效率。特别适合需要解决二维图像坐标与物理空间转换问题的自动化项目。

weixin_30664051的博客 407

ConcurrentModificationException 避免

背景: 在网络程序中经常遇到多个线程同时去操作一个集合Set,List.Map,Queue。Hashtable,Vector 在迭代集合的时候如何避免java.util.ConcurrentModificationException的发生。 以Hashtable为例,api中不是说Hashtable是同步的吗? 答:通过源码查看Hashtable中有一个keySet内部类,keySet对象又

javaee_ssh的专栏 7156

Win11 C盘爆满别慌!手把手教你安全迁移AppData和用户文件夹(附一键脚本)

本文针对Win11 C盘空间不足问题,提供了一套安全有效的解决方案。通过深入解析用户目录结构,指导用户利用符号链接和Robocopy工具,将AppData、下载文档等占用大户迁移至其他分区,并附带了自动化脚本,从根本上实现C盘瘦身,同时确保系统稳定和数据安全。

weixin_29231221的博客 2091

2024年11月架构设计师综合知识真题回顾,附参考答案、解析及所涉知识点(一)

软考高级考试包含三个科目:信息系统综合知识、系统架构设计案例分析和系统架构设计论文。考试形式为机考。本文主要回顾2024年下半年(2024-11-10)系统架构设计师考试上午综合知识科目的选择题,同时附带参考答案、解析和所涉知识点。由于机考时题目顺序是打乱的,本文题目所标序号只为区分不代表实际顺序。综合知识。

一几文的编程学习笔记。 9280

ConcurrentModificationException 并发修改异常的出现原因以及避免方法?

并发修改异常 (ConcurrentModificationException)出现原因: 在使用迭代器遍历集合的同时,使用集合对象增加集合的元素;迭代器是依赖集合而存在的,在判断成功后,集合中新增加了元素,而迭代器却不知道就报错了。 /** * 迭代器遍历 + 集合添加 * @param data */ public static void mixture(List<Integer> data) { for(Integer number : data) {

xuewei_ing的博客 699

基于Simulink的新能源汽车热管理系统设计与仿真详细介绍

新能源汽车(如纯电动汽车和混合动力汽车)的热管理系统是确保电池、电机和电控系统高效运行的关键。通过合理设计热管理系统,可以提高车辆的续航里程、延长电池寿命并提升整体性能。以下是如何在 MATLAB 和 Simulink 中设计并仿真一个新能源汽车热管理系统的详细步骤。通过上述步骤,我们成功设计并实现了基于 Simulink 的新能源汽车热管理系统。该系统能够根据目标温度和实际反馈,通过 PID 控制器或模糊控制器调整冷却液流量、风扇转速等参数,实现对电池、电机和车内的精确温度控制。

xiaoheshang_123的博客 385

java遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出

Java 必知必会 第 53 篇 遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出 问题: 在遍历集合的过程中,不会总出现ConcurrentModificationException异常的抛出,但是在下面的代码块中: public static void main(String[] args) { Collection<Intege...

十年互联网开发老兵,陪你一起学技术 643

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

避免低级错误:深入解析Java的ConcurrentModificationException异常

作为开发者,避免低级错误同样重要。希望本文能帮助读者更好地理解并解决异常,以及在开发中提高代码质量,减少不必要的问题发生。同时,重视测试工作,让我们的项目在实际应用中更加稳定和可靠。

修己xj的博客 535

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

List集合删除元素方式:避免java.util.ConcurrentModificationException异常

方式一,使用Iterator,顺序向下,如果找到元素,则使用remove方法进行移除。方式二,倒序遍历List,如果找到元素,则使用remove方法进行移除。方式三,正序遍历List,如果找到元素,则使用remove方法进行移除,然后进行索引“自减”。方式四,使用jdk1.8新增的Stream流操作。...

*** 棋了个怪_Rachel *** 2175

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

ConcurrentModificationException异常

一:ConcurrentModificationException异常: 当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。 二:遍历list集合时删除元素出现的异常 public static void main(String[] args) { ArrayList&lt;String&gt; list=new ArrayList&lt;String&gt;(); ...

小礼貌的博客 9万+

ConcurrentModificationException异常原理及有关处理

ConcurrentModificationException异常原理及有关处理

qq_46027570的博客 689

关于list的ConcurrentModificationException 异常

此类在源码中的注解为: /** * An {@code ConcurrentModificationException} is thrown when a Collection is * modified and an existing iterator on the Collection is used to modify the * Collection as well. */

999

java.util.ConcurrentModificationException异常处理

测试程序时,报java.util.ConcurrentModificationException异常。google后发现,是由于Iterator表示的哈希表变化造成的,代码如下: Iterator> iterator = hash.entrySet(); while (iterator.hasNext()) { ...... }在执行过程中,其他部分执行了hash.put或hash.remo

Nonetracer的专栏 891

Java ConcurrentModificationException 异常分析与解决方案

一、单线程 1. 异常情况举例     只要抛出出现异常,可以肯定的是代码一定有错误的地方。先来看看都有哪些情况会出现ConcurrentModificationException异常,下面以ArrayList remove 操作进行举例: 使用的数据集合: List myList = new ArrayList(); myList.add

Android 3万+

关于ConcurrentModificationException异常

在使用增强 for 循环遍历ArrayList,同时删除某元素时,遇到ConcurrentModificationException异常 for(Person p : personList) { if(id.equals(p.getId)) { personList.remove(p); } } 因为使用增强for循环的时候,内部原理是调...

weixin_30346033的博客 99

LinkedList 跑出的ConcurrentModificationException异常

LinkedList后台抛出了ConcurrentModificationException异常

smithdoudou88的专栏 3446

java.util.ConcurrentModificationException异常原因及解决方法

通过错误提示,知道了异常出现在checkForComodification这个方法上,异常原因是modCount!在网上查询得知,在很多容器中,都有一个变量记录你从结构上修改此容器的次数,叫做modCount,查看ArrayList的add()和remove()方法就可以发现,每次你调用add方法()向容器里面增加了一个元素,或者你调用Remove()方法删除了其中的某个元素,这个值都会增加1。

LYQ 6719

Java 遍历List ConcurrentModificationException 异常解析

ConcurrentModificationException 异常解析

益达还有么的博客 1万+

【小家java】Java中集合List、Set、Map删除元素的方法大总结(避免ConcurrentModificationException异常)

1、概述 java中的集合框架是我们日常使用得最多的数据结构,而List作为Collection里最重要的一员,使用就更加的频繁了。因此我们平时使用中少不了对List的增删改查,本文就针对于对List的“删”操作进行一个分析,顺便说几个坑,希望能帮助到大家以后可以避免踩坑 2、栗子 有一个List,如果我们要删除其中的一个元素,怎么办呢? 这里我们先用remove方法 3、使用场景...

架构师:通透,才能写出好代码! 2825
上一篇: android系统信息(内存、cpu、sd卡、电量、版本)获取
下一篇: 多条Notification更新,保持位置不变
nevercool
博客等级 码龄20年 4粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值