ArrayList 并发操作 ConcurrentModificationException 异常
1、故障现象
ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常
2、故障代码
public class ArrayListTest {
public static void main(String[] args) {
List<String> lists = new ArrayList<>();
lists.add("a");
lists.add("b");
Iterator<String> iterator = lists.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next == "b") {
lists.remove(next);
}
}
}
}
异常截图

3、导致原因
通过查看异常,发现异常出现的位置在 java.util.ArrayList类的内部类Itr中的checkForComodification方法中
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
通过查看代码发现如果 modCount和expectedModCount不相等就会导致抛出异常。
modCount是修改记录数,expectedModCount是期望修改记录数,初始化时expectedModCount=modCount。
ArrayList集合的add和remove操作都有对modCount++操作,就会导致expectedModCount和modCount值不相等从而产生ConcurrentModificationException异常
4、解决方案
解决方案1:使用iterator的remove操作替代ArrayList集合自己的remove操作
public class ArrayListTest {
public static void main(String[] args) {
List<String> lists = new ArrayList<>();
lists.add("a");
lists.add("b");
Iterator<String> iterator = lists.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next == "b") {
iterator.remove();
}
}
}
}
分析:通过查看iterator的remove方法发现,其实还是调用了ArrayList集合的remove方法移除元素,但是会使
expectedModCount=modeCount所以不会抛出ConcurrentModificationException异常
解决方案2:使用JUC concurrent包中CopyOnWriteArrayList并发集合类
public class ArrayListTest {
public static void main(String[] args) {
List<String> lists = new CopyOnWriteArrayList<>();
lists.add("a");
lists.add("b");
Iterator<String> iterator = lists.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (next == "b") {
lists.remove(next);
System.out.println(lists);
}
}
}
}
因为迭代器中没有checkForComodification操作,并且集合的add和remove方法中都通过ReentrantLock加锁保证并发操作下的安全性。
5、优化建议
在对ArrayList集合进行并发操作时尽量使用CopyOnWriteArrayList集合类代替
ArrayList 并发操作 ConcurrentModificationException 异常的更多相关文章
- 深入浅出 Java Concurrency (36): 线程池 part 9 并发操作异常体系[转]
并发包引入的工具类很多方法都会抛出一定的异常,这些异常描述了任务在线程池中执行时发生的例外情况,而通常这些例外需要应用程序进行捕捉和处理. 例如在Future接口中有如下一个API: java.uti ...
- Java并发编程:Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
- Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
- java集合--java.util.ConcurrentModificationException异常
ConcurrentModificationException 异常:并发修改异常,当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常.一个线程对collection集合迭代,另一个线程对Co ...
- 【转】Java ConcurrentModificationException 异常分析与解决方案--还不错
原文网址:http://www.2cto.com/kf/201403/286536.html 一.单线程 1. 异常情况举例 只要抛出出现异常,可以肯定的是代码一定有错误的地方.先来看看都有哪些情况会 ...
- 【转】Java ConcurrentModificationException异常原因和解决方法
原文网址:http://www.cnblogs.com/dolphin0520/p/3933551.html Java ConcurrentModificationException异常原因和解决方法 ...
- 修改List报ConcurrentModificationException异常原因分析
使用迭代器遍历List的时候修改List报ConcurrentModificationException异常原因分析 在使用Iterator来迭代遍历List的时候如果修改该List对象,则会报jav ...
- (转)Java ConcurrentModificationException异常原因和解决方法
转载自:http://www.cnblogs.com/dolphin0520/p/3933551.html 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会 ...
- 在ConcurrentModificationException异常上的联想
1.什么是ConcurrentModificationException? 大家都听说过快速报错fast-fail吧,fast-fail的发生就是说明发生了ConcurrentModification ...
随机推荐
- Win10下设置默认输入法与默认中文输入
实现的效果: 把自己需要的一个或多个输入法软件添加到输入法列表中(一般就指定一个),避免了需要在打字时Ctrl + Shift等快捷键在多个输入法中不停切换的麻烦 首选语言默认为中文,毕竟作为一个中国 ...
- Linux下扫描服务器IP地址是否冲突(arp-scan)
部署服务突然发现,连接的服务器断开了,因为服务器用户名密码是一样的,所以重新连接后,发现文件变了,跟之前不一样. 猜想是不是ip地址冲突了,两次连接的服务器不同. 网上查找资料说可以用工具扫描.工具: ...
- OpenJ_Bailian 7617 输出前k大的数
题目传送门 OpenJ_Bailian 7617 描述 给定一个数组,统计前k大的数并且把这k个数从大到小输出. 输入 第一行包含一个整数n,表示数组的大小.n < 100000.第二行包含n个 ...
- AtCoder Beginner Contest 151 题解报告
总的来说,这次的题目比较水,然而菜菜的我并没有把所有题目都做完,话不多说,直接来干货: A:Next Alphabet 题目链接:https://atcoder.jp/contests/abc151/ ...
- Spring中的beanPostProcess的作用
BeanPostProcessor是Spring框架中非常重要的bean之一.贯穿在Spring容器中bean的初始化的整个过程. Spring中的beanpostProcess体系结构如下: 可以看 ...
- 打造m3u8视频(流视频)下载解密合并器(kotlin)
本文是对我原创工具m3u8视频下载合并器关键代码解析及软件实现的思路的讲解,想要工具的请跳转链接 1.思路说明 思路挺简单,具体步骤如下: 下载m3u8文件 解析m3u8文件获得ts文件列表 根据文件 ...
- java 支持分词的高性能拼音转换工具,速度是 pinyin4j 的两倍
pinyin pinyin 是 java 实现的高性能中文拼音转换工具. 变更日志 创作目的 想为 java 设计一款便捷易用的拼音工具. 如何为 java 设计一款高性能的拼音转换工具 pinyin ...
- LCA - 倍增法去求第几个节点
You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, ...
- macOS 10.11.* 安装scrapy
1.安装brew,然后修改brew源为某高校 2.更新python brew install python 3.安装pip 4.安装scrapy,这里肯定会有一个坑,之前在网上看到10.11开启了什么 ...
- 【新书推荐】《ASP.NET Core微服务实战:在云环境中开发、测试和部署跨平台服务》 带你走近微服务开发
<ASP.NET Core 微服务实战>译者序:https://blog.jijiechen.com/post/aspnetcore-microservices-preface-by-tr ...