Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ConcurrentModificationException — prohibited modification during iteration

ConcurrentModificationException reports a detected modification that an object's contract forbids. It can occur in a single thread; it is neither a synchronization mechanism nor a guaranteed bug detector.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

java.util.ConcurrentModificationException
public class ConcurrentModificationException extends RuntimeException

ConcurrentModificationException in java.util extends RuntimeException and is unchecked. It reports a detected modification forbidden by an object's contract. Its name does not mean that another thread must be involved.

A fail-fast iterator can detect a collection change made outside that iterator. For ArrayList, adding and removing elements are structural changes; replacing a value with set is not. During iteration, remove through Iterator.remove() after a successful next(), at most once for that element.

Detection is best-effort: absence of the exception does not prove correctness. Do not base synchronization or program logic on catching it. Fix how the collection is modified; the catch in the example is only a demonstration.

The example first invalidates iterator stale through values.add(4), then calls stale.next(). A new iterator, current, safely removes even numbers. The expected output is ConcurrentModificationException, followed by [1, 3] on a separate line.

Examples

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

public class Main {
    public static void main(String[] args) {
        var values = new ArrayList<>(List.of(1, 2, 3));
        var stale = values.iterator();
        values.add(4);

        try {
            stale.next();
        } catch (ConcurrentModificationException ex) {
            System.out.println(ex.getClass().getSimpleName());
        }

        var current = values.iterator();
        while (current.hasNext()) {
            if (current.next() % 2 == 0) {
                current.remove();
            }
        }
        System.out.println(values);
    }
}

Result

ConcurrentModificationException
[1, 3]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources