今天在使用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會自己檢查修改操作,對其加鎖,也可針對插入操作。
