java.util.ConcurrentModificationException

Java8源码-详解fail-fast 细心地朋友看Java容器源码时一定会发现在list()和listIterator()的注释中都有一句话: The iterators returned by this class’s iterator and listIterator methods are fail-fast. 我看ArrayList源码没认真想fail-fast是什么意思,看Vector源码时又看到了这个词,而且... 阅读详情

当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。

例如,某个线程在 Collection 上进行迭代时,通常不允许另一个线性修改该 Collection。通常在这些情况下,迭代的结果是不明确的。如果检测到这种行为,一些迭代器实现(包括 JRE 提供的所有通用 collection 实现)可能选择抛出此异常。执行该操作的迭代器称为快速失败 迭代器,因为迭代器很快就完全失败,而不会冒着在将来某个时间任意发生不确定行为的风险。

注意,此异常不会始终指出对象已经由不同 线程并发修改。如果单线程发出违反对象协定的方法调用序列,则该对象可能抛出此异常。例如,如果线程使用快速失败迭代器在 collection 上迭代时直接修改该 collection,则迭代器将抛出此异常。

注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证。快速失败操作会尽最大努力抛出 ConcurrentModificationException。因此,为提高此类操作的正确性而编写一个依赖于此异常的程序是错误的做法,正确做法是:ConcurrentModificationException 应该仅用于检测 bug。


/*
 * @(#)ConcurrentModificationException.java	1.20 06/03/30
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.util;

/**
 * This exception may be thrown by methods that have detected concurrent
 * modification of an object when such modification is not permissible.
 * <p>
 * For example, it is not generally permissible for one thread to modify a Collection
 * while another thread is iterating over it.  In general, the results of the
 * iteration are undefined under these circumstances.  Some Iterator
 * implementations (including those of all the general purpose collection implementations
 * provided by the JRE) may choose to throw this exception if this behavior is
 * detected.  Iterators that do this are known as <i>fail-fast</i> iterators,
 * as they fail quickly and cleanly, rather that risking arbitrary,
 * non-deterministic behavior at an undetermined time in the future.
 * <p>
 * Note that this exception does not always indicate that an object has
 * been concurrently modified by a <i>different</i> thread.  If a single
 * thread issues a sequence of method invocations that violates the
 * contract of an object, the object may throw this exception.  For
 * example, if a thread modifies a collection directly while it is
 * iterating over the collection with a fail-fast iterator, the iterator
 * will throw this exception.
 *
 * <p>Note that fail-fast behavior cannot be guaranteed as it is, generally
 * speaking, impossible to make any hard guarantees in the presence of
 * unsynchronized concurrent modification.  Fail-fast operations
 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness: <i><tt>ConcurrentModificationException</tt>
 * should be used only to detect bugs.</i>
 *
 * @author  Josh Bloch
 * @version 1.20, 03/30/06
 * @see	    Collection
 * @see     Iterator
 * @see     ListIterator
 * @see	    Vector
 * @see	    LinkedList
 * @see	    HashSet
 * @see	    Hashtable
 * @see	    TreeMap
 * @see	    AbstractList
 * @since   1.2
 */
public class ConcurrentModificationException extends RuntimeException {
    /**
     * Constructs a ConcurrentModificationException with no
     * detail message.
     */
    public ConcurrentModificationException() {
    }

    /**
     * Constructs a <tt>ConcurrentModificationException</tt> with the
     * specified detail message.
     *
     * @param message the detail message pertaining to this exception.
     */
    public ConcurrentModificationException(String message) {
	super(message);
    }
}


一般List报错的原因:

Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。


源码:

AbstractList

	public E next() {
            checkForComodification();
	    try {
		E next = get(cursor);
		lastRet = cursor++;
		return next;
	    } catch (IndexOutOfBoundsException e) {
		checkForComodification();
		throw new NoSuchElementException();
	    }
	}

......

	final void checkForComodification() {
	    if (modCount != expectedModCount)
		throw new ConcurrentModificationException();
	}

......

protected transient int modCount = 0;

.....

int expectedModCount = modCount;


    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;



下面是Iterator的remove为什么不报错的原因:

    /**
     * Base class for Iterators for LinkedBlockingDeque
     */
    private abstract class AbstractItr implements Iterator<E> {
        /**
         * The next node to return in next
         */
         Node<E> next;

        /**
         * nextItem holds on to item fields because once we claim that
         * an element exists in hasNext(), we must return item read
         * under lock (in advance()) even if it was in the process of
         * being removed when hasNext() was called.
         */
        E nextItem;

        /**
         * Node returned by most recent call to next. Needed by remove.
         * Reset to null if this element is deleted by a call to remove.
         */
        private Node<E> lastRet;

        AbstractItr() {
            advance(); // set to initial position
        }

        /**
         * Advances next, or if not yet initialized, sets to first node.
         * Implemented to move forward vs backward in the two subclasses.
         */
        abstract void advance();

        public boolean hasNext() {
            return next != null;
        }

        public E next() {
            if (next == null)
                throw new NoSuchElementException();
            lastRet = next;
            E x = nextItem;
            advance();
            return x;
        }

        public void remove() {
            Node<E> n = lastRet;
            if (n == null)
                throw new IllegalStateException();
            lastRet = null;
            // Note: removeNode rescans looking for this node to make
            // sure it was not already removed. Otherwise, trying to
            // re-remove could corrupt list.
            removeNode(n);
        }
    }

    /** Forward iterator */
    private class Itr extends AbstractItr {
        void advance() {
            final ReentrantLock lock = LinkedBlockingDeque.this.lock;
            lock.lock();
            try {
                next = (next == null)? first : next.next;
                nextItem = (next == null)? null : next.item;
            } finally {
                lock.unlock();
            }
        }
    }

.....

    /**
     * Variant of removeFirstOccurrence needed by iterator.remove.
     * Searches for the node, not its contents.
     */
    boolean removeNode(Node<E> e) {
        lock.lock();
        try {
            for (Node<E> p = first; p != null; p = p.next) {
                if (p == e) {
                    unlink(p);
                    return true;
                }
            }
            return false;
        } finally {
            lock.unlock();
        }
    }


python编程实现制作网络流量监控动画 c,实时显示网络带宽使用情况,用柱状图或折线图表示不同时间段的流量变化。通过 Python编程实现图形库(如 Pygame、Tkinter、Matplotlib 等)来实现计算机网络基础概念的可视化动画。global bars # 声明 bars 为全局变量。# 获取当前网络流量。# 创建图形和坐标轴。 阅读详情

相关推荐

MediaPipe实战:从零构建人脸关键点检测应用

本文详细介绍了如何使用Google的MediaPipe框架从零构建一个实时人脸关键点检测应用。文章深入剖析了MediaPipe的三段式检测流水线,提供了Android平台的完整实战教程,包括环境配置、模型加载、摄像头集成、关键点绘制以及性能调优指南,帮助开发者快速实现高效、跨平台的人脸AR特效与交互功能。

weixin_29100927的博客 346

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

前言 二十多天的实训结束了,虽然环境emmmm有点坑,好多人都感冒了,我也没能逃过一劫. 不过总体来说还行, 第一次尝试跟学校里不一样的,7个人一起做项目. 不过也因此对于github的使用不再局限于之前的将其作为云服务备份来使用了,更多的还是大家上传代码,合并冲突之类的,还有也学会了git stash的一些个基础用法,嘻嘻. 这个月还没写点东西记录一下. 这里就记录一下之前遇到过的一个,算...

y4ung 23万+

大模型在心律失常预测及治疗方案制定中的应用研究报告

目录一、引言1.1 研究背景与意义1.2 研究目的与方法1.3 研究创新点二、大模型技术概述2.1 大模型基本原理2.2 常见大模型类型及特点2.3 大模型在医疗领域的应用现状三、心律失常的术前预测与准备3.1 术前心律失常预测的重要性3.2 大模型在术前预测中的应用案例3.3 基于预测结果的术前准备方案四、术中监测与实时调整4.1 术中监测心律失常的方法与技术4.2 大模型辅助术中决策的机制4.3 实时调整手术方案的策略与实践五、术后恢复与并发症风险预测5.1 术后心律失常的监测与评估5.2 大模型预测术

嵌入式毕设/课设资料清单(速查手册·文档模板·题库,持续更新)→ 见最新文章 1599

s:debug标签的错误ConcurrentModificationException

搭建SSH的时候页面上加入<s:debug>标签后台出现 严重: Servlet.service() for servlet jsp threw exceptionjava.util.ConcurrentModificationExceptionat java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859...

weixin_30802171的博客 126

使用 STM32F7 和 TensorFlow Lite 开发低功耗人脸识别设备

我们讨论了 STM32F7 的特点和能力,TensorFlow Lite 在 STM32F7 上的应用,以及一些降低功耗的优化技术。- 准备模型:选择合适的人脸识别模型,在 TensorFlow 中进行训练和导出,并使用 TensorFlow Lite 转换为适用于 STM32F7 的量化模型。请注意,上述代码仅展示了如何加载和运行 TensorFlow Lite 模型的方法,实际应用中需要集成人脸检测和识别模型,并根据实际需求进行相应的输入和输出处理。结合这两个工具,我们可以开发出低功耗的人脸识别设备。

weixin_66608063的博客 2589

STC8H8K64U ADC采样实战:从蜂鸣器控制到电压测量(附完整代码)

本文以STC8H8K64U单片机为核心,通过两个实战案例详细讲解ADC采样的应用。首先介绍如何利用ADC采样值动态控制蜂鸣器响度,实现模拟PWM效果;其次深入探讨高精度外部电压测量的方法,包括硬件连接、两点校准技巧以及软件滤波,旨在帮助开发者从理论到实践全面掌握ADC功能。

weixin_29159441的博客 563

如何完美解决 java.util.ConcurrentModificationException at java.util.LinkedHashMap$LinkedHashIterator.nex

在 Java 编程中,是一个常见的问题,特别是在使用集合类时。本篇文章将深入探讨这一异常的根本原因,并提供详细的解决方案和代码示例,帮助开发者快速排查和解决该问题。通过本文,您将学到如何避免此异常的发生,并提高代码的健壮性和效率。解决方案适用场景优点缺点Iterator 的 remove 方法单线程迭代时的删除操作简单易用不能处理多线程场景读多写少的场景线程安全,避免异常内存开销大,写操作性能低synchronized 块多线程修改同一集合的场景确保线程安全。

猫头虎技术团队:授渔优于赠鱼,兴趣引领智慧,探索之乐尤显珍贵。商务合作+:Libin9iOak ,万粉变现+:优快云WF,猫头虎承诺每年免费为100名C站创作者做账号流量诊断服务!全网搜:猫头虎技术团队,点击文章底部名片或直接私信我一切皆可谈,快找虎哥! 1万+

《跨界杂谈》华为印象(五):高度集权的矩阵式架构

高度集权的矩阵式架构 “高度集权的矩阵式架构”不是官方术语。是笔者的一位同事非常经典的总结。解释这个句话还是有点困难的,笔者入职华为三年也没彻底搞明白,在这里只能尝试性的解释一下。 矩阵 我们先看一下“矩阵”。华为有两套部门职能体系,华为内部术语,叫实线部门和虚线部门。由实线与虚线部门交叉构成矩阵。大部分(但不是所有)华为员工都由两个部门(两个领导)进行管理。对员工而言,所谓的实线部

《云计算架构技术与实践》 2998

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

增强for循环 遍历列表时会调用 checkForComodification() 方法检查当前列表是否有并发修改,如果有则会抛出 java.util.ConcurrentModificationException 异常。

晴空๓ 3001

STM32F407驱动OV2640摄像头:从SCCB协议到I2C模拟的保姆级避坑指南

本文详细介绍了STM32F407驱动OV2640摄像头的完整流程,重点解析SCCB协议与I2C的关键差异,并提供GPIO模拟实现方案。通过实战案例和调试技巧,帮助开发者避开常见陷阱,实现稳定的图像采集功能。

weixin_28700411的博客 349

超声波传感器(CHx01) 学习笔记 Ⅲ - I2C读写操作

CH-x01 通过 2 线 I2C 协议与主机处理器通信

nicole088的专栏 1740

java.util.ConcurrentModificationException(如何避免ConcurrentModificationException)

java.util.ConcurrentModificationException is a very common exception when working with java collection classes. Java Collection classes are fail-fast, which means if the Collection will be c...

WGH100817的博客 288

QML教程04 - Image:搞定界面上的所有图片

本文是QML教程系列的第四篇,重点讲解Image控件的实战用法。文章从图片显示常见的变形、卡顿等问题入手,详细介绍了Image的核心属性和使用技巧。主要内容包括:图片路径的三种写法(相对路径、qrc资源、网络URL)、最重要的fillMode属性解析(PreserveAspectFit、PreserveAspectCrop、Stretch的适用场景)、性能优化方法(sourceSize设置)、异步加载(asynchronous)以及圆形头像的实现方案。

BenBierBa的博客 1610

有关java.util.ConcurrentModificationException

有关java.util.ConcurrentModificationException java doc对这个类的定义: This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permiss

nobody 3197

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Java异常:Java.util.ConcurrentModificationException异常处理

在开发中使用了迭代器对 List 进行遍历,遇到了java.util.ConcurrentModificationException报错,本文记录了这个错误出现的原因和如何解决。

qq_46119575的博客 1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

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

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

3767

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java.util.ConcurrentModificationException 详解

问题出现 这次写代码写的比较急出现的一个问题,在遍历的时候使用Iterator在删除的时候用了List的remove,就出现了java.util.ConcurrentModificationException; public static void main(String[] args) { List<Integer> li=new ArrayList<Integer&g...

王者之峰 794

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

java.util.ConcurrentModificationException异常原因及解决方法 在项目中对List进行remove操作时报错java.util.ConcurrentModificationException 代码块: public static void main(String args[]) { Long id=Long.valueOf(200); ...

qq_25065295的博客 655

java程序报错 java.util.ConcurrentModificationException

先上图: 增强for和Iterator迭代 ArrayList时,用ArrayList的remove方法会报异常,java.util.ConcurrentModificationException 原因是: modCount是ArrayList的一个属性,继承自抽象类AbstractList,用于表示ArrayList对象被修改次数。整个ArrayList中修改modCount的方法比较多,有add、remove、clear、ensureCapacityInternal等,凡是设计到ArrayList对象

努力鸭~的博客 697

java.util.ConcurrentModificationException异常处理

对Vector、ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常 Caused by: java.util.ConcurrentModificationException eg: ArrayList mWidgets = new ArrayList; mWidgets.add(

Picasso_L的专栏 1203

java.util.ConcurrentModificationException 已解决

🌆。

扎哇太枣糕的笔记博客 957
上一篇: 什么是java序列化,如何实现java序列化?或者请解释Serializable接口的作用。
下一篇: 增强for循环
partner4java
博客等级 码龄17年 481粉丝 183原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值