android java.util.ConcurrentModificationException

2024-02-28 20:38

本文主要是介绍android java.util.ConcurrentModificationException,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

android  java.util.ConcurrentModificationException

 1.  使用 java.util.concurrent 包下的集合

      java.util.concurrent.ConcurrentHashMap;

      java.util.concurrent.CopyOnWriteArrayList;

      Please refer to http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html 

 

2. 循环 list or map 时 使用 iterator 来删除被循环的元素,或者将要删除或者增加的 元素先保存在一个临时集合里,待循环结束后再一次性操作,参考:  http://zhoujianghai.iteye.com/blog/1041555 

以下内容转发自:  http://zhoujianghai.iteye.com/blog/1041555 

 

iterator遍历集合时碰到java.util.ConcurrentModificationException这个异常,

下面以List为例来解释为什么会报java.util.ConcurrentModificationException这个异常,代码如下:

 

Java代码   收藏代码
  1. public static void main(String[] args) {  
  2.  List<String> list = new ArrayList<String>();  
  3.          list.add("1");  
  4.           list.add("2");  
  5.           list.add("3");  
  6.           list.add("4");  
  7.           list.add("5");  
  8.           list.add("6");  
  9.           list.add("7");  
  10.             
  11.  List<String> del = new ArrayList<String>();  
  12.           del.add("5");  
  13.           del.add("6");  
  14.           del.add("7");    
  15.   
  16. <span style="color: #ff0000;">for(String str : list){  
  17.      if(del.contains(str)) {  
  18.             list.remove(str);            
  19. }  
  20.           }</span>  
  21.  }  

 运行这段代码会出现如下异常:

 

Java代码   收藏代码
  1. Exception in thread "main" java.util.ConcurrentModificationException  

 

 

 for(String str : list) 这句话实际上是用到了集合的iterator() 方法

 JDK java.util. AbstractList类中相关源码

 

Java代码   收藏代码
  1. public Iterator<E> iterator() {  
  2.    return new Itr();  
  3. }  

 

 

java.util. AbstractList的内部类Itr的源码如下:

 

Java代码   收藏代码
  1. private class Itr implements Iterator<E> {  
  2.     /** 
  3.      * Index of element to be returned by subsequent call to next. 
  4.      */  
  5.     int cursor = 0;  
  6.   
  7.     /** 
  8.      * Index of element returned by most recent call to next or 
  9.      * previous.  Reset to -1 if this element is deleted by a call 
  10.      * to remove. 
  11.      */  
  12.     int lastRet = -1;  
  13.   
  14.     /** 
  15.      * The modCount value that the iterator believes that the backing 
  16.      * List should have.  If this expectation is violated, the iterator 
  17.      * has detected concurrent modification. 
  18.      */  
  19.     int expectedModCount = modCount;  
  20.   
  21.     public boolean hasNext() {  
  22.             return cursor != size();  
  23.     }  
  24.   
  25.     public E next() {  
  26.             checkForComodification(); //检测modCount和expectedModCount的值!!  
  27.         try {  
  28.         E next = get(cursor);  
  29.         lastRet = cursor++;  
  30.         return next;  
  31.         } catch (IndexOutOfBoundsException e) {  
  32.         checkForComodification();  
  33.         throw new NoSuchElementException();  
  34.         }  
  35.     }  
  36.   
  37.     public void remove() {  
  38.         if (lastRet == -1)  
  39.         throw new IllegalStateException();  
  40.             checkForComodification();  
  41.   
  42.         try {  
  43.         AbstractList.this.remove(lastRet); //执行remove的操作  
  44.         if (lastRet < cursor)  
  45.             cursor--;  
  46.         lastRet = -1;  
  47.         expectedModCount = modCount; //保证了modCount和expectedModCount的值的一致性,避免抛出ConcurrentModificationException异常  
  48.         } catch (IndexOutOfBoundsException e) {  
  49.         throw new ConcurrentModificationException();  
  50.         }  
  51.     }  
  52.   
  53.     final void checkForComodification() {  
  54.         if (modCount != expectedModCount) //当modCount和expectedModCount值不相等时,则抛出ConcurrentModificationException异常  
  55.         throw new ConcurrentModificationException();  
  56.     }  
  57.     }  

 

 

再看一下ArrayList 的 remove方法

 

Java代码   收藏代码
  1. public boolean remove(Object o) {  
  2.     if (o == null) {  
  3.             for (int index = 0; index < size; index++)  
  4.         if (elementData[index] == null) {  
  5.             fastRemove(index);  
  6.             return true;  
  7.         }  
  8.     } else {  
  9.         for (int index = 0; index < size; index++)  
  10.         if (o.equals(elementData[index])) {  
  11.             fastRemove(index);  
  12.             return true;  
  13.         }  
  14.         }  
  15.     return false;  
  16.     }  
  17.   
  18.     /* 
  19.      * Private remove method that skips bounds checking and does not 
  20.      * return the value removed. 
  21.      */  
  22.     private void fastRemove(int index) {  
  23.         modCount++; //只是修改了modCount,因此modCount将与expectedModCount的值不一致  
  24.         int numMoved = size - index - 1;  
  25.         if (numMoved > 0)  
  26.             System.arraycopy(elementData, index+1, elementData, index,  
  27.                              numMoved);  
  28.         elementData[--size] = null// Let gc do its work  
  29.     }   

 

 

回过头去看看java.util. AbstractListnext()方法

 

Java代码   收藏代码
  1. public E next() {  
  2.             checkForComodification(); //检测modCount和expectedModCount的值!!  
  3.         try {  
  4.         E next = get(cursor);  
  5.         lastRet = cursor++;  
  6.         return next;  
  7.         } catch (IndexOutOfBoundsException e) {  
  8.         checkForComodification();  
  9.         throw new NoSuchElementException();  
  10.         }  
  11.     }  
  12.    
  13. final void checkForComodification() {  
  14.         if (modCount != expectedModCount) //当modCount和expectedModCount值不相等时,则抛出ConcurrentModificationException异常  
  15.         throw new ConcurrentModificationException();  
  16.     }  
  17.     }  

 

 

现在真相终于大白了,ArrayListremove方法只是修改了modCount的值,并没有修改expectedModCount,导致modCountexpectedModCount的值的不一致性,当next()时则抛出ConcurrentModificationException异常

因此使用Iterator遍历集合时,不要改动被迭代的对象,可以使用 Iterator 本身的方法 remove() 来删除对象,Iterator.remove() 方法会在删除当前迭代对象的同时维护modCountexpectedModCount值的一致性。

 

 

解决办法如下:

(1)  新建一个集合存放要删除的对象,等遍历完后,调用removeAll(Collection<?> c)方法

把上面例子中迭代集合的代码替换成:

 

 

Java代码   收藏代码
  1. List<String> save = new ArrayList<String>();  
  2.             
  3.           for(String str : list)  
  4.           {  
  5.            if(del.contains(str))  
  6.            {  
  7.                save.add(str);  
  8.            }  
  9.           }  
  10.           list.removeAll(save);  

 

 

   (2) 使用Iterator替代增强型for循环:

 

Java代码   收藏代码
  1. Iterator<String> iterator = list.iterator();  
  2.      while(iterator.hasNext()) {  
  3.          String str = iterator.next();  
  4.          if(del.contains(str)) {  
  5.              iterator.remove();  
  6.          }  
  7.      }  

      Iterator.remove()方法保证了modCountexpectedModCount的值的一致性,避免抛出ConcurrentModificationException异常。

 

不过对于在多线程环境下对集合类元素进行迭代修改操作,最好把代码放在一个同步代码块内,这样才能保证modCountexpectedModCount的值的一致性,类似如下:

 

 

Java代码   收藏代码
  1. Iterator<String> iterator = list.iterator();    
  2. synchronized(synObject) {  
  3.  while(iterator.hasNext()) {    
  4.          String str = iterator.next();    
  5.          if(del.contains(str)) {    
  6.              iterator.remove();    
  7.          }    
  8.      }    
  9. }  
  10.       

 

因为迭代器实现类如:ListItr的next(),previous(),remove(),set(E e),add(E e)这些方法都会调用checkForComodification(),源码:

 

 

Java代码   收藏代码
  1. final void checkForComodification() {  
  2.         if (modCount != expectedModCount)  
  3.         throw new ConcurrentModificationException();  
  4.     }  

 

 

 

 

 

 

曾经写了下面这段对HashMap进行迭代删除操作的错误的代码:

 

Java代码   收藏代码
  1. Iterator<Integer> iterator = windows.keySet().iterator();  
  2.         while(iterator.hasNext()) {  
  3.             int type = iterator.next();  
  4.             windows.get(type).closeWindow();  
  5.             iterator.remove();  
  6.             windows.remove(type);   //  
  7.         }  

 

 上面的代码也会导致ConcurrentModificationException的发生。罪魁祸首是windows.remove(type);这一句。

根据上面的分析我们知道iterator.remove();会维护modCountexpectedModCount的值的一致性,而windows.remove(type);这句是不会的。其实这句是多余的,上面的代码去掉这句就行了。

iterator.remove()的源码如下:HashIterator类的remove()方法

 

 

Java代码   收藏代码
  1. public void remove() {  
  2.             if (lastEntryReturned == null)  
  3.                 throw new IllegalStateException();  
  4.             if (modCount != expectedModCount)  
  5.                 throw new ConcurrentModificationException();  
  6.             HashMap.this.remove(lastEntryReturned.key);  
  7.             lastEntryReturned = null;  
  8.             expectedModCount = modCount; //保证了这两值的一致性  
  9.         }  

 HashMap.this.remove(lastEntryReturned.key);这句代码说明windows.remove(type);是多余的,因为已经删除了该key对应的value。

windows.remove(type)的源码:

 

 

Java代码   收藏代码
  1. public V remove(Object key) {  
  2.         if (key == null) {  
  3.             return removeNullKey();  
  4.         }  
  5.         int hash = secondaryHash(key.hashCode());  
  6.         HashMapEntry<K, V>[] tab = table;  
  7.         int index = hash & (tab.length - 1);  
  8.         for (HashMapEntry<K, V> e = tab[index], prev = null;  
  9.                 e != null; prev = e, e = e.next) {  
  10.             if (e.hash == hash && key.equals(e.key)) {  
  11.                 if (prev == null) {  
  12.                     tab[index] = e.next;  
  13.                 } else {  
  14.                     prev.next = e.next;  
  15.                 }  
  16.                 modCount++;  
  17.                 size--;  
  18.                 postRemove(e);  
  19.                 return e.value;  
  20.             }  
  21.         }  
  22.         return null;  
  23.     }  

 上面的代码中,由于先调用了iterator.remove();所以再调用HashMap的remove方法时,key就已经为null了,所以会执行:removeNullKey();

方法,removeNullKey()源码:

 

 

Java代码   收藏代码
  1. private V removeNullKey() {  
  2.        HashMapEntry<K, V> e = entryForNullKey;  
  3.        if (e == null) {  
  4.            return null;  
  5.        }  
  6.        entryForNullKey = null;  
  7.        modCount++;  
  8.        size--;  
  9.        postRemove(e);  
  10.        return e.value;  
  11.    }  

 不过不管是执行removeNullKey()还是key != null,如果直接调用HashMap的remove方法,都会导致ConcurrentModificationException

这个异常的发生,因为它对modCount++;没有改变expectedModCount的值,没有维护维护索引的一致性。

 

下面引用一段更专业的解释:

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

这篇关于android java.util.ConcurrentModificationException的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2