java.util.ConcurrentModificationException的解决办法

  今天在使用iterator.hasNext()操作迭代器的时候,当迭代的对象发生改变,比如插入了新数据,或者有数据被删除。

编译器报出了以下异常:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:719)
	at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:752)
	at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:750)
	at DBOperating.norStaticRelations(DBOperating.java:88)
	at DBOperating.insertintoDB(DBOperating.java:79)
	at Main.main(Main.java:51)

 例如以下程序:

import java.util.*;  
  
public class Main  
{  
public static void main(String args[])  
{  
Main main = new Main();  
main.test();  
}  
  
public void test()  
{  
Map aa = new HashMap();  
a.put("1", "111");  
aa.put("2", "222");  
Iterator it = aa.keySet().iterator();  
while(it.hasNext()) {  
Map.Entry entry = (Map.Entry) it.next();  
            aa.remove(ele);    //此处报错 
}  
System.out.println("运行成功!");  
}  
}  

  

分析原因:Iterator做遍历的时候,HashMap被修改(aa.remove(ele), size-1),Iterator(Object ele=it.next())会检查HashMap的size,size发生变化,抛出错误ConcurrentModificationException。

解决办法:

1) 通过Iterator修改Hashtable
while(it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
            it.remove();
}

2) 根据实际程序,您自己手动给Iterator遍历的那段程序加锁,给修改HashMap的那段程序加锁。


3) 使用“ConcurrentHashMap”替换HashMap,ConcurrentHashMap会自己检查修改操作,对其加锁,也可针对插入操作。

 

原文地址:https://www.cnblogs.com/wangkundentisy/p/6659321.html