一.参考
1.Java Essentials: Preventing ConcurrentModificationException
https://www.codebyamir.com/blog/java-essentials-preventing-concurrentmodificationexception

二.
Overview
The JVM will throw a ConcurrentModificationException at runtime whenever we try to modify a collection while iterating over it.

In this article, we’ll explain why this happens and some solutions to prevent this.

Example
Suppose we populate a list with names and then later want to remove some names from the list.

Code
We may write something like this:

List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

for (String name : names) {
if (name.startsWith(“A”)) {
names.remove(name);
}
}

System.out.println(names);
Output
This code will compile successfully but throw an exception at runtime on line 10:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayList I t r . c h e c k F o r C o m o d i f i c a t i o n ( U n k n o w n S o u r c e ) a t j a v a . u t i l . A r r a y L i s t Itr.checkForComodification(Unknown Source) at java.util.ArrayList Itr.checkForComodification(UnknownSource)atjava.util.ArrayListItr.next(Unknown Source)
at com.codebyamir.demo.Main.main(Main.java:10)
Notice that this may only happen intermittently because we are calling remove() inside a conditional statement. So the exception will be thrown whenever we have a String that starts with “A” in our list.

Solutions
There are a number of ways to prevent ConcurrentModificationException, and we’ll explore these below.

Use an Iterator
We can change how we iterate by replacing the enhanced for-loop with a while loop that uses an Iterator object. The Iterator allows us to safely remove the matching element because we are not calling remove() directly on the list object.

Code
List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

Iterator iter = names.iterator();

while (iter.hasNext()) {
String name = iter.next();

if (name.startsWith(“A”)) {
iter.remove();
}
}

System.out.println(names);
Output
[Beth, Lucy]

Populate a separate list to keep track of the items to be removed
This approach avoids having to introduce an Iterator object, but it requires another list to keep track of the names we want to remove.

Code
List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

List removeNames = new ArrayList<>();

for (String name : names) {
if (name.startsWith(“A”)) {
removeNames.add(name);
}
}

names.removeAll(removeNames);
Output
[Beth, Lucy]

Use Java 8’s removeIf() method
Java 8 added the removeIf() method to the java.util.Collection class.

JDK Code
Let’s take a look at the JDK code for this method. Notice how it uses an Iterator under the hood.

public boolean removeIf(Predicate paramPredicate) {
Objects.requireNonNull(paramPredicate);
boolean bool = false;
Iterator localIterator = iterator();
while (localIterator.hasNext()) {
if (paramPredicate.test(localIterator.next())) {
localIterator.remove();
bool = true;
}
}
return bool;
}
Code
This method makes our code more concise since we can use a Lambda expression.

List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

names.removeIf(name -> (name.startsWith(“A”)));
Output
[Beth, Lucy]

Note that ArrayList has an optimized implementation of `removeIf`` (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java/#1393) which makes it the fastest solution.

Java Essentials: Preventing ConcurrentModificationException相关推荐

  1. 如何在Java中处理ConcurrentModificationException? 在循环中从ArrayList中删除元素时要当心...

    从Java中从ArrayList中删除元素时常见的问题之一是ConcurrentModificationException. 如果您对索引使用经典的for循环或增强的for循环,并尝试使用remove ...

  2. Java集合的ConcurrentModificationException

    简单复习一下集合顺带提一下这个错误,其实也比较常见,大多是因为疏忽的原因吧: 我们创建一个集合,添加了一些元素,使用迭代器来遍历,然后遍历途中需要进行一些逻辑操作,对集合进行修改,然后就报错了,这是什 ...

  3. 幻数java题_java – ConcurrentModificationException的幻数

    首先要知道的是(如 JLS所述)以下增强的for循环: for (String s : list) { // Do something with s } 相当于: for (Iterator it = ...

  4. 【集合】Java 集合的ConcurrentModificationException

    文章目录 1.美图 2.概述 2.1 操作(这三种情况都会报错) 2.1.1 第1种错误情况 2.1.2 第2种错误情况 2.1.2 第3种错误情况 2.2.现象(错误信息) 3.原因 4.Array ...

  5. mega_[MEGA DEAL] Android课程的Java基础知识(61%折扣)

    mega 与大学教授一起掌握Android应用背后的语言! 嘿,怪胎, 本周,在我们的JCG Deals商店中,我们提供了一个极端的报价. 我们提供的Java Essentials for Andro ...

  6. foreach去除重复元素java_Java foreach 中List移除元素抛出ConcurrentModificationException原因全解析...

    本文重点探讨 foreach 循环中List 移除元素造成 java.util.ConcurrentModificationException 异常的原因. 先看<阿里巴巴 Java开发手册&g ...

  7. 【集合】JDK 7 HashMap集合的ConcurrentModificationException 原因

    文章目录 1.概述 2. 解决 1.概述 首先参考文章:[集合]Java 集合的ConcurrentModificationException 下面再看一个案例 /*** 测试点:测试hashmap的 ...

  8. java开发课程表_Java开发人员课程包,折扣高达86%

    java开发课程表 Java is by far the most widely used programming language and it's very popular too. There ...

  9. 集合collection

    集合体系结构 1.Collection 1.1.collection集合概述和使用 collection集合概述 Collection是单列集合的顶层接口,他表示一组对象,这些对象也称为Collect ...

最新文章

  1. CYQ.Data.ProjectTool 项目配置工具发布(包源码)
  2. 【深度学习笔记】SIFT特征和SURF特征比较
  3. 【湖南】2021年下半年软考报考时间及通知
  4. Log4j的快速入门
  5. SAP CRM Pricing Procedure中的Doc和Customer Procedure在哪里维护
  6. 前端学习(1860)vue之电商管理系统电商系统之渲染login组件并且实现路由重定向
  7. opensource项目_一月份的Opensource.com预览
  8. Android Studio(9)--添加应用资源
  9. springboot上传文件同时传参数_Spring Boot 系列:使用 Spring Boot 上传文件
  10. 20200703:将有序数组转换为二叉搜索树(leetcode108)
  11. 士林变频器面板如何调速度_必读干货丨西威变频器DRIVE OVERLOAD故障处理
  12. 电驴搜索服务器正在连接,电驴emule eD2k 不能连接服务器解决办法
  13. Mixly第三方自定义用户库实现
  14. AutoCAD VBA 通过选择集 删除图层上所有对象和图层
  15. 信息安全工程实践笔记--Day1 信息收集漏洞扫描
  16. MyBatis万能插入语句
  17. Siege 简单教程
  18. 东望时代(原中国建筑第一股浙江广厦),将换域名,升级官网为数字化网站
  19. Object oriented Design
  20. 老九C++零基础学习(二)变量声明和使用

热门文章

  1. 各向异性方解石晶体的双折射效应
  2. 毕设 CC2530+esp8266使用AT指令上传与获取onenet服务器的数据
  3. OpenCV 3与ROS兼容、OpenCV多版本共存
  4. solid works装配图带约束导入Adams中
  5. Google翻译API(B/S调用和C/S调用)
  6. python 列表索引从1开始,在Python中,列表索引值是从1开始。
  7. 硅谷文化,逆生长在西湖?
  8. Mybatis动态数据源实现
  9. 使用Java实现玩家和电脑猜丁壳
  10. android 内存溢出解决方法,android内存溢出解决