Emergence of java.util.ConcurrentModificationException problems and solutions

  • 2020-06-07 04:27:01
  • OfStack

java.util.ConcurrentModificationException solution

Preface:

When using iterator.hasNext () to operate an iterator, if the iterated object changes at this point, such as new data is inserted or data is deleted.

If used, the following exceptions will be reported:


Java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$KeyIterator.next(HashMap.java:828)

For example, the following program (transferred from the Internet) :


mport java.util.*; 
 
public class Main 
{ 
public static void main(String args[]) 
{ 
Main main = new Main(); 
main.test(); 
} 
 
public void test() 
{ 
Map bb = new HashMap(); 
bb.put("1", "wj"); 
bb.put("2", "ry"); 
Iterator it = bb.keySet().iterator(); 
while(it.hasNext()) { 
Object ele = it.next(); 
      bb.remove(ele);  //wrong 
} 
System.out.println("Success!"); 
} 
} 

Reason: When Iterator is doing the traversal, HashMap is modified (bb. remove(ele), size-1), Iterator(Object ele= it. next()) checks HashMap's size, size is changed and throws an error ConcurrentModificationException.

Solutions:

1) Modify Hashtable through Iterator


while(it.hasNext()) {
Object ele = it.next();
      it.remove();
}

2) According to the actual program, you manually lock the program traversed by Iterator and the program modified by HashMap.

3) Replace HashMap with "ConcurrentHashMap". ConcurrentHashMap will check the modification operation by itself, lock it, and also for insert operation.


import java.util.concurrent.*;

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: