Library contents

Groovy ConcurrentModificationException

An ArrayList iterator can detect structural changes made to the list outside the iterator.

A simple example

ConcurrentModificationException

  1. Start with An iterator is traversing a list
  2. Do this Change the list directly, then advance the iterator
  3. Result Can report concurrent modification
A fail-fast iterator may detect a structural change. Its own supported removal method keeps traversal coordinated.

Syntax

Groovy syntax
inspection.next()
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Remove an expired pass during inspection

A clerk walks through a list of travel passes to remove expired entries. Editing the list behind an active iterator can invalidate its position, so the cleanup needs an iteration strategy that supports removal.

Result[valid]
Lesson.groovy
import java.util.ArrayList
import java.util.ConcurrentModificationException

def passes = new ArrayList<>(["expired", "valid"])
def inspection = passes.iterator()
passes.remove("expired")
try {
    inspection.next()
} catch (ConcurrentModificationException problem) {
    println(passes)
}
Output
[valid]

The expired pass was removed through the list. The stale iterator detects the change before it returns another pass.

Advertisements

Clear a cancelled rehearsal

Both entries in a rehearsal list are marked off. Use the iterator to remove cancelled entries during review. How many names remain?

Givenoff · off
Worked result0

Keep a confirmed gallery helper

One gallery helper is confirmed and one has cancelled. Use the iterator to remove cancelled entries during review. How many names remain?

Givenyes · off
Worked result1

What to watch for

This fail-fast check is best effort. Use iterator.remove or a collection removal operation for intentional edits.

Documentation for ConcurrentModificationException