Open In App

How to Avoid ConcurrentModificationException in Java?

Last Updated : 16 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections,  i.e whenever we try to modify an object concurrently without permission  ConcurrentModificationException occurs which is present in java.util package.

Procedure: Some steps are required in order to avoid the occurrence of this exception in a single-threaded environment. They are as follows:

  • Instead of iterating through collections classes, we can iterate through the arrays. This works perfectly fine for smaller lists what about the bigger list? It’s very basic we know that if the array size is huge then it affects the performance. Hence, this method is only effective for smaller size arrays.
  • The next method is the Synchronized block method, Here we actually lock the list in a synchronized block to avoid the exception. Isn’t that cool? but guess what this is also not an effective method to avoid Exception Why? Because the purpose of multithreading is not being used.
  • The better way is we have ConcurrentHashMap and CopyOnWriteArrayList Which is the best among the above Methods.

Methods:

Here two ways are proposed of which starting with the naive one and ending up with the optimal approach to reach the goal.

  1. Using Loops: We used the Iterator remove() method instead of that we can use a for loop to avoid ConcurrentModificationException in a Single-threaded environment. If we add any extra objects then we can ensure that our code takes care of them.
  2. Using the remove() Method: We can use the remove method to remove the object from the collection. Here there is a problem that is you can  only remove the same object and not any other from the list

Example 1:

Java




// Java Program to Avoid
// AvoidConcurrentModificationException
 
// Importing Map and List utility classes
//  from java.util package
import java.util.List;
import java.util.Map;
 
// Importing classes from java.util.concurrent package
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of List class
        // Declaring object of string type
        List<String> marvel
            = new CopyOnWriteArrayList<String>();
 
        // Adding elements to the above object created
        // Custom input entries
        marvel.add("IronMan");
        marvel.add("BlackWidow");
        marvel.add("Hulk");
        marvel.add("DoctorStrange");
        marvel.add("SpiderMan");
 
        // Iterating over object created using size() method
        for (int i = 0; i < marvel.size(); i++) {
 
            // Print and display the object elements
            // using get() method
            System.out.println("Avenger : "
                               + marvel.get(i));
 
            // Condition check over object elements
 
            // If specific element is matched
            if (marvel.get(i).equals("BlackWidow")) {
 
                marvel.remove(i);
                i--;
 
                // Add this specific element
                marvel.add("CaptianAmerica");
            }
        }
 
        // Now getting the final total size by checking
        // how many elements are there inside object
        System.out.println("Total Avengers : "
                           + marvel.size());
    }
}


 
 

Output

Avenger : IronMan
Avenger : BlackWidow
Avenger : Hulk
Avenger : DoctorStrange
Avenger : SpiderMan
Avenger : CaptianAmerica
Total Avengers :5

Note: The Exception can also occur if we try to modify the structure of original list with sublist. An example for the same is below,

 

Example 2:

 

Java




// Java Program to Illustrate ConcurrentModificationException
// WithArrayListSubList
 
// Importing List and Arraylist classes utility classes
// from java.util package
import java.util.ArrayList;
import java.util.List;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Creating a List class object
        // Declaring object of string type
        List <String> names = new ArrayList <>();
 
        // Adding elements to the object of List class
 
        // Custom input entries
        names.add("Java");
        names.add("C++");
        names.add("Phython");
        names.add("JavaScript");
 
        List < String > first2Names = names.subList(0, 2);
 
        System.out.println(names + " , " + first2Names);
 
        names.set(1, "Ruby");
 
        // check the output below. 🙂
        System.out.println(names + " , " + first2Names);
 
        // Now we add another string to
        // get ConcurrentModificationException
        names.add("SQL");
 
        // This line throws an exception
        System.out.println(names + " , " + first2Names);
 
    }
}


 
 

Output:

 

 

Henceforth, we have discussed how to avoid the Exception in both single-threaded and multithreaded environments successfully as depicted from the above outputs. 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads