Search code examples
javaconcurrencyconcurrentmodification

ConcurrentModificationException, clarification needed


The following mockup code ends up in ConcurrentModificationException, that happens (as i understand it), due to the fact that i am iterating over a set, which i am modifying.

Set<String> data = new HashSet<String>();
data.add("a=1");
data.add("b=2");
data.add("c=3");
data.add("d=4");

for (String s : data) {
    data.remove(s);
}

But why is it exactly? Please help clarify


Solution

  • You're violating the iterator's contract. From the ConcurrentModificationException javadoc,

    If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.