ConcurrentModificationException in Java with Examples

ConcurrentModificationException in Multi threaded environment

In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown.

  1. If this exception is detected, then the results of the iteration are undefined.
  2. Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators.

For example: If we are trying to modify any collection in the code using a thread, but some another thread is already using that collection, then this will not be allowed.

ConcurrentModificationException in Single threaded environment

Since, there is no guarantee that whenever this exception is raised, an object is been under concurrent modification by some different thread, this exception is also thrown in the single-threaded environment.



If we invoke a sequence of methods on an object that violates its contract, then the object throws ConcurrentModificationException.

For example: if while iterating over the collection, we directly try to modify that collection, then the given fail-fast iterator will throw this ConcurrentModificationException.

Example: In the following code, an ArrayList is implemented. Then few values are added to it and few modifications are made over it while traversing,

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to show
// ConcurrentModificationException
  
import java.util.Iterator;
import java.util.ArrayList;
  
public class modificationError {
    public static void main(String args[])
    {
  
        // Creating an object of ArrayList Object
        ArrayList<String> arr
            = new ArrayList<String>();
  
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        arr.add("Four");
  
        try {
            // Printing the elements
            System.out.println(
                "ArrayList: ");
            Iterator<String> iter
                = arr.iterator();
  
            while (iter.hasNext()) {
  
                System.out.print(iter.next()
                                 + ", ");
  
                // ConcurrentModificationException
                // is raised here as an element
                // is added during the iteration
                System.out.println(
                    "\n\nTrying to add"
                    + " an element in "
                    + "between iteration\n");
                arr.add("Five");
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

chevron_right


Output:

ArrayList: 
One, 

Trying to add an element in between iteration

java.util.ConcurrentModificationException

How to avoid ConcurrentModificationException?

To avoid this exception,

Example: Let’s see how to resolve this exception by simply changing the place of modification.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to show
// ConcurrentModificationException
  
import java.util.Iterator;
import java.util.ArrayList;
  
public class modificationError {
    public static void main(String args[])
    {
  
        // Creating an object of ArrayList Object
        ArrayList<String> arr
            = new ArrayList<String>();
  
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        arr.add("Four");
  
        try {
            // Printing the elements
            System.out.println(
                "ArrayList: ");
            Iterator<String> iter
                = arr.iterator();
  
            while (iter.hasNext()) {
                System.out.print(iter.next()
                                 + ", ");
            }
  
            // No exception is raised as
            // a modification is done
            // after the iteration
            System.out.println(
                "\n\nTrying to add"
                + " an element in "
                + "between iteration: "
                + arr.add("Five"));
  
            // Printing the elements
            System.out.println(
                "\nUpdated ArrayList: ");
            iter = arr.iterator();
  
            while (iter.hasNext()) {
                System.out.print(iter.next()
                                 + ", ");
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

chevron_right


Output:

ArrayList: 
One, Two, Three, Four, 

Trying to add an element in between iteration: true

Updated ArrayList: 
One, Two, Three, Four, Five,

From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.