java.util.ConcurrentModificationException solution

  • 2020-05-27 07:46:46
  • OfStack

java.util.ConcurrentModificationException solution

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

When 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 (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 traversing, HashMap is modified (bb.remove (ele), size-1), Iterator(Object ele= it.next ()) will check size of HashMap, size changes, and ConcurrentModificationException throws an error.

Solutions:

1) modify Hashtable via Iterator


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

2) according to the actual program, you manually lock the program that Iterator traverses and the program that changes HashMap.

3) replace HashMap with "ConcurrentHashMap". ConcurrentHashMap will check the modification operation and lock it, or it can be used for insert operation.
import java.util.concurrent.*;

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


Related articles: