Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ConcurrentModificationexception
3.
Why ConcurrentModificationexception occurs?
4.
Constructors of ConcurrentModificationException 
5.
Examples of ConcurrentModificationEcxeption
6.
Impact of ConcurrentModification Exception
7.
Mitigate the impact of ConcurrentModification Exception
8.
How to prevent ConcurrentModification Exception?
9.
Frequently Asked Questions
9.1.
How do I iterate over a collection and modify it safely?
9.2.
Are there any alternatives to ConcurrentModificationException for concurrent collections?
9.3.
Can we catch a ConcurrentModificationException?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

ConcurrentModificationException

Author Tashmit
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

While coding in Java programming, encountering an exception is a common occurrence. One of the common exceptions is ConcurrentModificationException.  

ConcurrentModificationException

In this article, we will study the ConcurrentModification Exception in Java. We will discuss why this exception occurs, what are its impacts, and how we can prevent it.

What is ConcurrentModificationexception

In Java, ConcurrentModification Exception is a runtime exception. It occurs when a collection is modified when it is iterated. When we are working with lists, sets, or maps, we can encounter this error. 

Let us now see why this exception occurs. 

Also read, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why ConcurrentModificationexception occurs?

In most of the collection classes, iterators are already provided. But when we modify the structure, there is a chance that the ConcurrentModificationexception occurs.

When we modify the iterator using the next() function, we can remove, update, or add elements. Although, the iterator keeps a record of the expected state and throws an exception when it detects any structural modification.

Also see,  Eclipse ide for Java Developers

Constructors of ConcurrentModificationException 

There are mainly 4 types of constructors in ConcurrentModificationException:

  1. public ConcurrentModificationException(); This constructor generates a ConcurrentModificationException with no parameters.
     
  2. public ConcurrentModificationException(String message): It generates a ConcurrentModificationException with a detailed message which specifies the Exception.
     
  3. public ConcurrentModificationException(Throwable cause): It generates a ConcurrentModificationException with a cause and a message which is (cause==null?null:cause.toString()).
     
  4. public ConcurrentModificationException(String message, Throwable cause): It generates a ConcurrentModificationException with a detailed message and a cause (cause==null?null:cause.toString()).

Examples of ConcurrentModificationEcxeption

Let us understand this with a code snippet:

Code

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConcurrentModificationExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("Coding");
        list.add("Ninjas");

        Iterator<String> iterator = list.iterator();

        while (iterator.hasNext()) {
            String str = iterator.next();
            System.out.println(str);

            if (str.equals("Coding")) {
                list.add("How are you?"); //ConcurrentModificationException
            }
        }
    }
}


Output

Output

Explanation

In the above example, we can clearly see that we are trying to modify the list structurally during the iteration process. So, it will throw ConcurrentModificationException.

Also see, Hashcode Method in Java and Java Ioexception

Impact of ConcurrentModification Exception

Some of the main impacts of encountering a ConcurrentModificationException:

  1. Program terminate: Whenever the Concurrent Modification Exception is encountered, the program terminates. 
     
  2. Debugging and Troubleshooting: The ConcurrentModification Exception helps in finding the issues. Thus, it makes it easier to identify and debug the code.
     
  3. Stability and Reliability: Java helps to maintain the stability and reliability of code once the exception is thrown. It resists errors and ensures the data integrity of data is preserved.

Mitigate the impact of ConcurrentModification Exception

In order to mitigate the impact of a ConcurrentModificationException we must:

  • Check and review the code properly. Also, we must ensure that the modification to a collection is not performed during interactions.
     
  • If there is the need to apply ConcurrentModification, make sure we use synchronisation mechanism.
     
  • Always try to use appropriate iterators and their dependent methods.

How to prevent ConcurrentModification Exception?

In order to prevent ConcurrentModificationException in Java, we must follow:

  1. Use synchronised collection: We must use the synchronised collection from the java.util.collection if multiple threads are accessing a collection. These collections provide a thread-safe operation that prevents the modification and, thus the exception.
     
  2. Use Concurrent collections: In Java, there are many specialised concurrent collections already available. Try to use those collections as they are optimised for high-concurrency scenarios.
     
  3. Use enhanced loop: When we need to only read and not modify elements we must use the enhanced for loop. This loop does not throw any exception as it do not allow modifications.

Must Read, even number program in java

Read more, how to run java program

Frequently Asked Questions

How do I iterate over a collection and modify it safely?

In order to iterate over a collection, we must use the appropriate techniques. It includes using an iterator's remove() method or creating a separate collection to store modifications.

Are there any alternatives to ConcurrentModificationException for concurrent collections?

In java.util.concurrent there are alternatives to concurrent collections. The package ConcurrentHashMap or CopyOnWriteArrayList, is made to take care of concurrent modifications without throwing a ConcurrentModificationException.

Can we catch a ConcurrentModificationException?

Yes, we can catch a ConcurrentModificationException using a try-catch block. 

Conclusion

In this article, we studied about the ConcurrentModification Exception in Java. We discussed about why this exception occurs, what are its impacts and how we can prevent it. To know more, you can refer to Exception in Java.

You may refer to our Guided Path on Coding Ninjas Studio for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy learning, Ninja! 

Previous article
How to Use the Javac Command
Next article
Difference between Class and Interface
Live masterclass