How to Avoid ConcurrentModificationException in Java?
Last Updated :
16 Jun, 2021
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.
- 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.
- 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
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class GFG {
public static void main(String[] args)
{
List<String> marvel
= new CopyOnWriteArrayList<String>();
marvel.add( "IronMan" );
marvel.add( "BlackWidow" );
marvel.add( "Hulk" );
marvel.add( "DoctorStrange" );
marvel.add( "SpiderMan" );
for ( int i = 0 ; i < marvel.size(); i++) {
System.out.println( "Avenger : "
+ marvel.get(i));
if (marvel.get(i).equals( "BlackWidow" )) {
marvel.remove(i);
i--;
marvel.add( "CaptianAmerica" );
}
}
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
import java.util.ArrayList;
import java.util.List;
public class GFG {
public static void main(String[] args) {
List <String> names = new ArrayList <>();
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" );
System.out.println(names + " , " + first2Names);
names.add( "SQL" );
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
Share your thoughts in the comments
Please Login to comment...