ConcurrentModificationException产生原因的情况解析

本文主要是介绍ConcurrentModificationException产生原因的情况解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


产生这个异常,归根结底的原因是因为,一个list或者集合 在遍历的同时进行了 写或者删除操作,改变了 list的大小:

    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;


        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();
            }
        }


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


 }

造成这个现象的原因:

1 简单直接的原因,遍历的时候进行了增 删操作

for (String str : list) {

list.add(s); 

or 

list.remove(0);

}

2. 还有一种情况 就是一个list 在多线程环境先,被不同的线程在遍历的同时,进行了增删操作

/**
 * 中文转汉语拼音
 * 支持多音字
 */
public class HanyuPinyinHelper {


    private static StringBuffer buffer;
    private static List<String> list;
    private static Properties p;
    private static boolean isSimple;


    static{
        buffer = new StringBuffer();
        list = new ArrayList<String>();
        p = new Properties();
        isSimple=false;
        try {
            p.load(new BufferedInputStream(HanyuPinyinHelper.class
                    .getResourceAsStream("/hanyu_pinyin.txt")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    public static String[] getHanyuPinyins(char c) {
        int codePointOfChar = c;
        String codepointHexStr = Integer.toHexString(codePointOfChar)
                .toUpperCase();
        String str = (String) p.get(codepointHexStr);
        return str.split(",");
    }


    /**
     * @param str 需要转换的字符串
     * @param isSimple true简拼,false全拼
     * @return 该字符串转换后的所有组合
     */
    public static List<String> hanyuPinYinConvert(String str,boolean isSimpleFlag) {
        if (str == null || "".equals(str))
            return null;
        isSimple=isSimpleFlag;
        list.clear();
        buffer.delete(0, buffer.length());
        convert(0, str);
        return list;
    }




    /**
     * @param str 需要转换的字符串
     * @return 该字符串转换后的所有组合,包含全拼和简拼
     */
    public static List<String> hanyuAllPinYinConvert(String str) {
        if (str == null || "".equals(str))
            return null;
        list.clear();
        buffer.delete(0, buffer.length());
        isSimple=true;
        convert(0, str);
        buffer.delete(0, buffer.length());
        isSimple=false;
        convert(0, str);
        return list;
    }


    private static void convert(int n, String str) {
        if (n == str.length()) {// 递归出口
            String temp=buffer.toString();
            if(!list.contains(temp)){
                list.add(buffer.toString());
            }
            return;
        } else {
            char c = str.charAt(n);
            if (0x3007 == c || (0x4E00 <= c && c <= 0x9FA5)) {// 如果该字符在中文UNICODE范围
                String[] arrayStrings = getHanyuPinyins(c);
                if (arrayStrings == null) {
                    buffer.append(c);
                    convert(n + 1, str);
                } else if (arrayStrings.length == 0) {
                    buffer.append(c);
                    convert(n + 1, str);
                } else if (arrayStrings.length == 1) {
                    if(isSimple){
                        if(!"".equals(arrayStrings[0])){
                            buffer.append(arrayStrings[0].charAt(0));
                        }
                    }else{
                        buffer.append(arrayStrings[0]);
                    }
                    convert(n + 1, str);
                } else {
                    int len;
                    for (int i = 0; i < arrayStrings.length; i++) {
                        len = buffer.length();
                        if(isSimple){
                            if(!"".equals(arrayStrings[i])){
                                buffer.append(arrayStrings[i].charAt(0));
                            }
                        }else{
                            buffer.append(arrayStrings[i]);
                        }
                        convert(n + 1, str);
                        buffer.delete(len, buffer.length());
                    }
                }
            } else {// 非中文
                buffer.append(c);
                convert(n + 1, str);
            }
        }
    }


    public static void main(String[] args) {
        List list1 = HanyuPinyinHelper.hanyuAllPinYinConvert("瞿乐底");
        System.out.println(list1);


    }


}


这篇关于ConcurrentModificationException产生原因的情况解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/605432

相关文章

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

SpringBoot中的404错误:原因、影响及解决策略

《SpringBoot中的404错误:原因、影响及解决策略》本文详细介绍了SpringBoot中404错误的出现原因、影响以及处理策略,404错误常见于URL路径错误、控制器配置问题、静态资源配置错误... 目录Spring Boot中的404错误:原因、影响及处理策略404错误的出现原因1. URL路径错

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的