Library contents

Scala 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

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

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

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.scala
import java.util.ArrayList
import java.util.ConcurrentModificationException

object Lesson {
    def main(args: Array[String]): Unit = {
        val passes = new ArrayList[String]()
        passes.add("expired")
        passes.add("valid")
        val inspection = passes.iterator()
        passes.remove("expired")
        try {
            inspection.next()
        } catch {
            case 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