Last Updated:

How do I avoid ConcurrentModificationException when using Iterator?

Today, we're going to look at a way to avoid using the . This situation most often occurs when you use an iterator to walk through the elements of the collection and at some point the call will be thrownThis situation can occur in both multithreaded and single-threaded environments.

ConcurrentModificationExceptionIteratoriterator.next()ConcurrentModificationException

Let's look at this with a simple example:

The output of this code is as follows:

Based on the results of the execution, the exception occurs at the time when we call the method of our iterator.next()

Want to know how to check the number of changes in a collection? Here's a little background: Iterator

The class has a variable where the number of changes to the list is stored. This value is used in each subsequent method call to check for any changes to the .AbstractListmodCountnext()checkForComodification()

And now let's comment out the part of the code with the error, run the program again and see the following result:

Since we are updating an existing element in MyMap, its size has not changed, hence we are not getting . Note that the result of running the program may differ on your system because the HashMap key set () is not ordered as a list. If you uncomment the part of the code where we add a new element to , it will cause .ConcurrentModificationExceptionkeysetHashMapConcurrentModificationException

And now practical tips:

How to Avoid ConcurrentModificationException in a Multithreaded Environment

  1. You can convert the list to an array, and work with the array. This approach works well for a small to medium-sized list, but if the list is large, then it will greatly affect performance.
  2. You can lock the list while items are crawled by pasting it into a synchronized block. This approach is not recommended because it will simply kill the benefits of multithreading.
  3. You can use the classes and . This is the most effective and correct approach.ConcurrentHashMapCopyOnWriteArrayList

How to Avoid ConcurrentModificationException in a Single-Threaded Environment

In a multithreaded environment, you can use the method to delete an object. But in this case, you can only delete the current object, not any other object from the list.remove()

Let's look at an example

The result will be as follows:

 

Findings

  1. Thread-safe collections avoid ConcurrentModificationException
  2. In the case of CopyOnWriteArrayList, the iterator will work with the initial list.
  3. In the case of ConcurrentHashMap, the behavior is not always the same.

The result of executing such code:

It will be as follows:

If you change the code above to this:

Then we get the following:

Now you know how to avoid ConcurrentModificationException when using Iterator.