How to Avoid ConcurrentModificationException in Java?
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.
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
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,
Henceforth, we have discussed how to avoid the Exception in both single-threaded and multithreaded environments successfully as depicted from the above outputs.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.