Avoid “ConcurrentModificationException” when collection is modified while it is been iterated over by multiple threads.

Damith Neranjan Samarakoon
Javarevisited
Published in
2 min readFeb 22, 2023

Hello folks, in this post I’m about to discuss how to avoid “ConcurrentModificationException” when modifying collections. Let’s move with this,

The ConcurrentModificationException is thrown when a collection is modified while it is being iterated over by multiple threads, or by the same thread in some cases.

Let me explain this with following example.

public void setData(final Map<String, Object> data) {
this.data = new HashMap<>();
for (final Map.Entry<String, Object> entry: data.entrySet()) {
this.data.put(entry.getKey() , entry.getValue());
}
}

In this case, it seems that the ‘data ‘ map is being modified while it is being iterated over, leading to the exception.

One way to avoid this exception is to create a copy of the map before iterating over it. We have already attempted to create a new HashMap in the code, but we are still iterating over the original map, which may be causing the issue. To fix this, we can modify our code as follows:

public void setData(final Map<String, Object> data) {
this.data = new HashMap<>(data.size()); // Create a new HashMap with the same size as the original map
for (final Map.Entry<String, Object> entry : new HashMap<>(data).entrySet()) {
this.data.put(entry.getKey(), entry.getValue());
}
}

In this modified code, we are creating a new HashMap with the same size as the original map. We are also creating a new copy of the data map using the constructor new HashMap<>(data), which creates a shallow copy of the original map. This ensures that any modifications made to the data map during the iteration will not affect the copy, thereby preventing the ConcurrentModificationException.

Note that creating a shallow copy of the map may not be sufficient if the values in the map are themselves mutable objects. In that case, you may need to create deep copies of the objects as well to prevent concurrent modification issues.

Thanks for reading and happy coding ..!! 🙂

--

--

Damith Neranjan Samarakoon
Javarevisited

I’m an Engineering Lead @Persistent System, blogger,thinker, husband & father of “little angle”. passionate about Technology,Engineering and Learning.