ConcurrentModificationException is one of the most common runtime exceptions in Java, especially when working with the Java Collections Framework. It typically occurs when a collection such as an ArrayList, HashSet, or HashMap is modified while it is being iterated.
Many Java beginners assume that this exception only happens in multithreaded applications because of the word “Concurrent”, but that’s not true. In fact, ConcurrentModificationException often occurs in single-threaded programs when a collection is structurally modified during iteration.
In this guide, you’ll learn what ConcurrentModificationException is, why it occurs, common causes, practical examples, and the best ways to fix and prevent it.
What is ConcurrentModificationException?
ConcurrentModificationException is a runtime exception that belongs to the java.util package.
It is thrown when a collection detects that it has been modified while an iterator is traversing it, except through the iterator’s own remove() method.
Example error:
Exception in thread “main”
java.util.ConcurrentModificationException
This exception acts as a fail-fast mechanism, helping developers detect incorrect modifications to collections early.
Why Does ConcurrentModificationException Occur?
Most Java collections use fail-fast iterators.
When an iterator is created, it internally stores a modification count (modCount) of the collection.
If the collection is structurally modified outside the iterator while iteration is in progress, the iterator detects that the modification count has changed and throws:
java.util.ConcurrentModificationException
Structural modifications include:
- Adding elements
- Removing elements
- Clearing the collection
Updating an existing element (without changing the collection size) usually does not trigger this exception.
Common Causes of ConcurrentModificationException
Some common reasons include:
- Removing elements inside a for-each loop.
- Adding elements during iteration.
- Modifying a collection while another thread is iterating over it.
- Calling collection.remove() instead of iterator.remove().
- Nested iteration with structural modifications.
- Using fail-fast collections incorrectly.
Example That Causes ConcurrentModificationException
Consider the following code:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> removeList = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
for (String language : list) {
if (language.equals("Python")) {
list.remove(language);
}
}
}
}
Output:
java.util.ConcurrentModificationException
The exception occurs because the collection is modified while the enhanced for loop is iterating over it.
How Fail-Fast Iterators Work
Most collections such as:
- ArrayList
- HashMap
- HashSet
- LinkedList
use fail-fast iterators.
Internally:
- The iterator stores the current modification count.
- Before every iteration, it compares the stored count with the collection’s current count.
- If they differ, the iterator throws ConcurrentModificationException.
This mechanism prevents unpredictable behavior.
Solution 1: Use Iterator.remove()
The safest way to remove elements during iteration is to use the iterator itself.
Correct example:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("Java");
list.add("Python");
list.add("C++");
List<String> removeList = new ArrayList<>();
while (iterator.hasNext()) {
String language = iterator.next();
if (language.equals("Python")) {
iterator.remove();
}
}
System.out.println(list);
}
}
Output:
Since the iterator performs the removal, no exception occurs.
Solution 2: Use removeIf() (Java 8+)
Java 8 introduced the convenient removeIf() method.
Example:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> removeList = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.removeIf(language -> language.equals("Python"));
System.out.println(list);
}
}
Output:
This is often the cleanest solution.
Solution 3: Iterate Over a Copy
Instead of modifying the original collection, iterate over a copy.
Example:
List<String> removeList = new ArrayList<>();
for (String language : copy) {
if (language.equals("Python")) {
list.remove(language);
}
}
Since the iterator belongs to the copied collection, the original collection can be modified safely.
Solution 4: Collect Elements First
Instead of removing elements immediately, collect them first.
Example:
List<String> removeList = new ArrayList<>();
for (String language : list) {
if (language.equals("Python")) {
removeList.add(language);
}
}
list.removeAll(removeList);
for (String language : list) {
if (language.equals("Python")) {
removeList.add(language);
}
}
list.removeAll(removeList);
This approach avoids modifying the collection during iteration.
Solution 5: Use CopyOnWriteArrayList
For concurrent applications, Java provides thread-safe collections.
Example:
import java.util.concurrent.CopyOnWriteArrayList;
CopyOnWriteArrayList<String> list =
new CopyOnWriteArrayList();
Unlike ArrayList, this collection allows safe modification during iteration because it creates a new copy of the internal array whenever the collection changes.
However, it is best suited for applications with many reads and few writes, as copying the array has performance and memory costs.
Solution 6: Synchronize Collection Access
When multiple threads access the same collection, synchronize access.
Example:
List<String> list =
Collections.synchronizedList(new ArrayList());
Synchronization helps prevent race conditions, but you must still synchronize while iterating:
synchronized (list) {
for (String item : list) {
System.out.println(item);
}
}
Solution 7: Use Streams Carefully
Instead of modifying the existing collection, create a filtered one.
Example:
List<String> filtered =
list.stream()
.filter(language -> !language.equals("Python"))
.toList();
This approach avoids structural modification during iteration.
Solution 8: Avoid Nested Modifications
Incorrect:
for (String value : list) {
list.add("Java");
}
Adding elements while iterating almost always results in ConcurrentModificationException.
Instead, complete the iteration first and modify the collection afterward.
Solution 9: Understand Structural vs Non-Structural Changes
Structural modifications:
- add()
- remove()
- clear()
Usually safe:
list.set(0, "Java Programming");
Replacing an existing value without changing the collection size typically does not trigger the exception.
Solution 10: Choose the Right Collection
Some collections are better suited for concurrent modifications.
Examples include:
- CopyOnWriteArrayList
- ConcurrentHashMap
- ConcurrentLinkedQueue
- ConcurrentSkipListMap
Selecting the appropriate collection depends on your application’s concurrency requirements.
Real-World Example
Incorrect implementation:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List numbers = new ArrayList();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (Integer number : numbers) {
if (number == 20) {
numbers.remove(number);
}
}
}
}
Output:
java.util.ConcurrentModificationException
Correct implementation:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List numbers = new ArrayList();
numbers.add(10);
numbers.add(20);
numbers.add(30);
Iterator iterator =
numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next();
if (number == 20) {
iterator.remove();
}
}
System.out.println(numbers);
}
}
Output:
| Scenario | Solution |
|---|---|
| Removing inside a for-each loop | Use Iterator.remove() |
| Multiple threads modifying a collection | Use thread-safe collections |
| Removing using collection.remove() | Use iterator.remove() |
| Frequent concurrent reads and writes | Use CopyOnWriteArrayList if appropriate |
| Filtering elements | Use removeIf() or Streams |
| Nested modification | Separate iteration and modification |
| Shared mutable collections | Synchronize access or use concurrent collections |
Best Practices to Prevent ConcurrentModificationException
Follow these recommendations:
- Never modify a collection directly inside a for-each loop.
- Use Iterator.remove() when removing elements during iteration.
- Prefer removeIf() for simple filtering operations.
- Choose concurrent collections for multithreaded applications.
- Avoid unnecessary structural modifications.
- Use immutable collections whenever possible.
- Synchronize shared collections correctly.
- Keep iteration and modification separate.
- Test collection code under concurrent conditions.
- Understand the behavior of fail-fast iterators.
Frequently Asked Questions (FAQs)
Is ConcurrentModificationException only related to multithreading?
No. Despite its name, it commonly occurs in single-threaded programs when a collection is modified during iteration.
Which collections throw ConcurrentModificationException?
Common fail-fast collections include:
- ArrayList
- LinkedList
- HashMap
- HashSet
- TreeMap
- TreeSet
How do I safely remove elements while iterating?
Use the iterator’s remove() method:
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals("Python")) {
iterator.remove();
}
}
Alternatively, use removeIf() in Java 8 and later.
Does CopyOnWriteArrayList throw ConcurrentModificationException?
No. CopyOnWriteArrayList uses a snapshot-based iterator that allows safe iteration even when the collection is modified. However, because each modification creates a new copy of the underlying array, it is most efficient for scenarios with frequent reads and infrequent writes.
Conclusion
ConcurrentModificationException is a fail-fast runtime exception that helps developers detect unsafe modifications to Java collections during iteration. Although it often surprises beginners, it is straightforward to avoid by understanding how iterators work. The safest approaches include using Iterator.remove(), leveraging removeIf() for simple filtering, iterating over a copy when necessary, and choosing thread-safe collections such as CopyOnWriteArrayList or ConcurrentHashMap for concurrent applications. By following these best practices, you can write cleaner, safer, and more reliable Java code when working with collections.