Today, when using the Iterator.hasnext () operation iterator, when the object of the iteration changes, such as inserting new data, or having data deleted.
The compiler reported the following exception:
Exception in thread "main" Java.util.ConcurrentModificationExceptionat 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)
For example, the following programs:
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); Error here} System.out.println ("Run successfully!"); } }
Analysis Reason: Iterator do traversal, HashMap is modified (Aa.remove (ele), size-1), Iterator (Object ele=it.next ()) will check HashMap size,size change, Throws an error concurrentmodificationexception.
Workaround:
1) Modify the Hashtable by iterator
while (It.hasnext ()) {
Map.entry Entry = (map.entry) it.next ();
It.remove ();
}
2) According to the actual program, you manually to the iterator traversal of the program lock, to modify the HashMap of the program and lock.
3) Replace Hashmap,concurrenthashmap with "Concurrenthashmap" to check for modifications, lock them, or insert them.
Solutions to Java.util.ConcurrentModificationException