Solutions to Java.util.ConcurrentModificationException

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.