Library contents

Kotlin 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

Kotlin 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.jar

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.kt
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)
    }
}
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