Java ConcurrentModificationException exception Analysis and Solution

Source: Internet
Author: User
Tags concurrentmodificationexception






I. Single-thread 1. Exceptions as long as an exception is thrown, it is certain that the code is wrong. First, let's take a look at the situations where ConcurrentModificationException occurs. The following uses the ArrayList remove operation as an example:

Data Set used:
           List
 
   myList = new ArrayList
  
   ();           myList.add( "1");           myList.add( "2");           myList.add( "3");           myList.add( "4");           myList.add( "5");
  
 

Exceptions may occur in the following three cases:
           Iterator
 
   it = myList.iterator();            while (it.hasNext()) {                String value = it.next();                 if (value.equals( "3")) {                     myList.remove(value);  // error                }           }                  for (Iterator
  
    it = myList.iterator(); it.hasNext();) {                String value = it.next();                 if (value.equals( "3")) {                     myList.remove(value);  // error                }           }                        for (String value : myList) {                System. out.println( "List Value:" + value);                 if (value.equals( "3")) {                     myList.remove(value);  // error                }           }   
  
 

The exception information is as follows:
Exception in thread "main" java. util. ConcurrentModificationException
At java. util. AbstractList $ Itr. checkForComodification (Unknown Source)
At java. util. AbstractList $ Itr. next (Unknown Source)


2. the preceding three root causes have a common feature: Iterator is used for traversal, and ArrayList. remove (Object) is used for deletion.
To find out the root cause, check the ArrayList source code to see why an exception occurs:
Public class ArrayList
 
  
Extends actlist
  
   
Implements Cloneable, Serializable, RandomAccess {@ Override public boolean remove (Object object Object) {object [] a = array; int s = size; if (Object! = Null) {for (int I = 0; I <s; I ++) {if (object. equals (a [I]) {System. arraycopy (a, I + 1, a, I, -- s-I); a [s] = null; // Prevent memory leak size = s; modCount ++; // If the deletion is successful, return true; }}} else {for (int I = 0; I <s; I ++) {if (a [I] = null) {System. arraycopy (a, I + 1, a, I, -- s-I); a [s] = null; // Prevent memory leak size = s; modCount ++; // If the deletion is successful, return true;} return false;} @ Override public Iterator
   
    
Iterator () {return new ArrayListIterator ();} private class ArrayListIterator implements Iterator
    
     
{...... // Save The total number of global modifications to The current class/** The expected modCount value */private int expectedModCount = modCount; @ SuppressWarnings ("unchecked") public E next () {ArrayList
     
      
OurList = ArrayList. this; int rem = remaining; // if the value at creation is different, an exception is thrown if (ourList. modCount! = ExpectedModCount) {throw new ConcurrentModificationException ();} if (rem = 0) {throw new NoSuchElementException ();} remaining = rem-1; return (E) ourList. array [removalIndex = ourList. size-rem] ;}......}
     
    
   
  
 

List, Set, and Map can all be traversed through Iterator. Here we only use the List example. When using other sets to perform the addition and deletion operations, you must be aware of whether the ConcurrentModificationException will be triggered.


3. the solution lists several problems that may occur, and analyzes the root cause of the problem. Let's summarize what is correct, concurrentModificationException does not occur if you do not perform the add or delete operation on the duration.
// 1 use the remove method provided by Iterator to delete the current element for (Iterator
 
  
It = myList. iterator (); it. hasNext ();) {String value = it. next (); if (value. equals ("3") {it. remove (); // OK} System. out. println ("List Value:" + myList. toString (); // 2. Create a set, record the elements to be deleted, and delete the List in a unified manner.
  
   
Templist = new ArrayList
   
    
(); For (String value: myList) {if (value. equals ("3") {templist. remove (value) ;}// you can view the removeAll source code. Use Iterator to traverse the myList. removeAll (templist); System. out. println ("List Value:" + myList. toString (); // 3. use thread-safe CopyOnWriteArrayList to delete the operation List
    
     
MyList = new CopyOnWriteArrayList
     
      
(); MyList. add ("1"); myList. add ("2"); myList. add ("3"); myList. add ("4"); myList. add ("5"); Iterator
      
        It = myList. iterator (); while (it. hasNext () {String value = it. next (); if (value. equals ("3") {myList. remove ("4"); myList. add ("6"); myList. add ("7") ;}} System. out. println ("List Value:" + myList. toString (); // 4. if you do not use Iterator for traversal, you must ensure that the index is normal for (int I = 0; I <myList. size (); I ++) {String value = myList. get (I); System. out. println ("List Value:" + value); if (value. equals ("3") {myList. remove (value); // OK I --; // because the position changes, you must modify the I position} System. out. println ("List Value:" + myList. toString ());
      
     
    
   
  
 

All output results are: List Value: [1, 2, 4, 5]. No exception occurs.
The above four solutions can be tested in a single thread, but what if they are in multiple threads?


Ii. multithreading 1. an example of synchronization exceptions the above four solutions are proposed for ConcurrentModificationException in the case of a single thread. This solution can have a pleasant experience, however, the multi-threaded environment may be less optimistic.
In the following example, two subthreads are enabled, one for traversal and the other for conditional deletion:
Final List
 
  
MyList = createTestData (); new Thread (new Runnable () {@ Override public void run () {for (String string: myList) {System. out. println ("traversal set value =" + string); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();}}}}). start (); new Thread (new Runnable () {@ Override public void run () {for (Iterator
  
   
It = myList. iterator (); it. hasNext ();) {String value = it. next (); System. out. println ("delete element value =" + value); if (value. equals ("3") {it. remove ();} try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();}}}}). start ();
  
 

Output result:
Traversal set value = 1
Delete element value = 1
Traversal set value = 2
Delete element value = 2
Traversal set value = 3
Delete element value = 3
Exception in thread "Thread-0" delete element value = 4
Java. util. ConcurrentModificationException
At java. util. AbstractList $ Itr. checkForComodification (Unknown Source)
At java. util. AbstractList $ Itr. next (Unknown Source)
At list. ConcurrentModificationExceptionStudy $ 1.run( ConcurrentModificationExceptionStudy. java: 42)
At java. lang. Thread. run (Unknown Source)
Delete element value = 5


Conclusion:
In the preceding example, only the 1st solutions that are deleted in single-thread traversal use it in the case of multithreading. remove (), but the test shows that 1, 2, and 3 of the Four Solutions still have problems.
Next let's take a look at JavaDoc's description of java. util. ConcurrentModificationException:
This exception is thrown when the method detects concurrent object modifications but does not allow such modifications.
It indicates that the above method is normal when the same thread is executed, but exceptions may still occur in asynchronous mode.


2. solution (1) Add synchronized to all traversal additions and deletions or use Collections. although synchronizedList can solve the problem, it is not recommended because the synchronization lock caused by addition or deletion may block the traversal operation.
(2) ConcurrentHashMap or CopyOnWriteArrayList is recommended.


3. Notes about CopyOnWriteArrayList (1) CopyOnWriteArrayList cannot be deleted using Iterator. remove.
(2) CopyOnWriteArrayList uses Iterator and List. remove (Object); The following exception occurs:
Java. lang. UnsupportedOperationException: Unsupported operation remove
At java. util. concurrent. CopyOnWriteArrayList $ ListIteratorImpl. remove (CopyOnWriteArrayList. java: 804)

4. solution 4 solutions are listed in single-threaded mode, but only 4th solutions are available in multi-threaded mode.
List
 
  
MyList = new CopyOnWriteArrayList
  
   
(); MyList. add ("1"); myList. add ("2"); myList. add ("3"); myList. add ("4"); myList. add ("5"); new Thread (new Runnable () {@ Override public void run () {for (String string: myList) {System. out. println ("traversal set value =" + string); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();}}}}). start (); new Thread (new Runnable () {@ Override public void run () {for (int I = 0; I <myList. size (); I ++) {String value = myList. get (I); System. out. println ("delete element value =" + value); if (value. equals ("3") {myList. remove (value); I --; // note} try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();}}}}). start ();
  
 


Output result:
Delete element value = 1
Traversal set value = 1
Delete element value = 2
Traversal set value = 2
Delete element value = 3
Traversal set value = 3
Delete element value = 4
Traversal set value = 4
Delete element value = 5
Traversal set value = 5

OK.



Iii. References: How to Avoid ConcurrentModificationException when using an Iterator

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.