Kotlin ConcurrentModificationException
An ArrayList iterator can detect structural changes made to the list outside the iterator.
A simple example
ConcurrentModificationException
- Start with An iterator is traversing a list
- Do this Change the list directly, then advance the iterator
- Result Can report concurrent modification
Syntax
inspection.next()
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarRemove 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.
import java.util.ArrayList
import java.util.ConcurrentModificationException
fun main() {
val passes = arrayListOf("expired", "valid")
val inspection = passes.iterator()
passes.remove("expired")
try {
inspection.next()
} catch (problem: ConcurrentModificationException) {
println(passes)
}
}
[valid]
The expired pass was removed through the list. The stale iterator detects the change before it returns another pass.
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?
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?
What to watch for
This fail-fast check is best effort. Use iterator.remove or a collection removal operation for intentional edits.