← Back to list

Avoiding ConcurrentModificationException in Java

Have you ever encountered a cryptic ConcurrentModificationException in your Java code? This exception can be a real head-scratcher…

Bibek Poudel in Stackademic · 2024-04-03 12:32 · 0 claps · 1.9 min read
#java #concurrentmodification #collection #exception
Open on Medium ↗

Avoiding ConcurrentModificationException in Java

Photo by Diana Polekhina on Unsplash

Photo by Diana Polekhina on Unsplash

Have you ever encountered a cryptic ConcurrentModificationException in your Java code? This exception can be a real head-scratcher, especially when dealing with collections and multithreading. But fear not, this blog post will shed light on this common pitfall and equip you with techniques to avoid it!

Understanding the Exception:

Imagine you’re iterating through a list of items like groceries, checking them off one by one. Suddenly, someone removes an item from the middle of the list while you’re halfway through. This unexpected change throws off your count and creates confusion. Similarly, the ConcurrentModificationException arises when you try to modify a collection (like a list or map) while simultaneously iterating over it using an iterator. Java collections maintain internal structures to track their elements. Modifications during iteration disrupt this tracking, leading to the exception.

Example of Concurrent Modification Exception:

package com.workflex.mobile.webservice;

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

public class Test {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");

        for (String elem : list) {
            if (elem.equals("a")) {
                list.remove(elem); //concurrent modification exception
            }
        }
    }

}

How to Avoid Concurrent Modification Exception:

Use Synchronized Collections: One way to avoid Concurrent Modification Exception is by using synchronized collections provided by Java Collections framework. These collections ensure that only one thread can access the collection at a time, preventing concurrent modification issues.

import java.util.Collections;
import java.util.List;

List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());

Use Concurrent Collections: Java provides concurrent collections like ConcurrentHashMap and CopyOnWriteArrayList, which are designed to be safely used in concurrent environments without causing Concurrent Modification Exception.

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();

Iterating with Iterator: If modification of the collection is necessary, use Iterator instead of foreach loop for iterating. Iterator’s remove() method can be safely used to remove elements during iteration without causing Concurrent Modification Exception.

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
    Integer number = iterator.next();
    if (number == 2) {
        iterator.remove(); // Safe removal using Iterator
    }
}

Iterate with a copy: Create a copy of the original collection before iterating. This allows you to modify the copy without affecting the iteration on the original collection.

ArrayList<String> namesCopy = new ArrayList<>(names);
for (String name : namesCopy) {
  // Now you can safely modify names based on name
}

Remember: By following these techniques, you can ensure smooth sailing while modifying collections during iteration in your Java programs, avoiding the dreaded ConcurrentModificationException. Now, go forth and conquer your collections with confidence!

Stackademic 🎓

Thank you for reading until the end. Before you go:


메타데이터
post_id
28d7d86c261a
slug
avoiding-concurrentmodificationexception-in-java-28d7d86c261a
url
https://blog.stackademic.com/avoiding-concurrentmodificationexception-in-java-28d7d86c261a
canonical_url
https://blog.stackademic.com/avoiding-concurrentmodificationexception-in-java-28d7d86c261a
author_url
https://medium.com/@bibeknese0
status
ok
fetched_at
2026-08-01 14:51:42