DevOps / Apache Groovy Interview questions
How do you troubleshoot a ConcurrentModificationException in Groovy collections?
Groovy's collection literals and GDK methods operate on standard Java collection types under the hood, so the same rule applies as in plain Java: modifying a collection, adding or removing elements, while iterating over it directly with each, for, or an iterator will throw this exception, since the underlying iterator detects the structural change mid-iteration.
A common, Groovy-specific trap is doing this inside a closure passed to each or findAll - it's easy to overlook that the closure is iterating live over the original collection, especially when the modifying call is buried a few lines into the closure body rather than obviously adjacent to the iteration itself.
The fix is usually to iterate over a copy, like list.toList() or a new ArrayList(list), when modification during iteration is needed, or better, to use a transformation method that returns a new collection instead of mutating in place - using collect or findAll to build a new filtered/transformed list rather than removing elements from the original while iterating it.
If genuinely concurrent, multi-threaded, modification is the actual cause rather than same-thread iteration-plus-mutation, a thread-safe collection type or explicit synchronization is needed instead - iterating over a copy alone doesn't fix a true multi-threaded race, since another thread could still be mutating the original list at the same time.
More Related questions...