BackendBench
Coffee
Spot the Bug #23

Adding while forEach is running

A medium Java puzzle in the modifying while iterating family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumModifying while iteratingbuggy line: 6

Highlighted: line 6. Play this one as a puzzle without the answer.

What is wrong

ArrayList.forEach checks for modification after the loop and throws ConcurrentModificationException when the lambda changes the list. Streams and forEach are not safe places to mutate their own source.

The fix

List<Integer> extra = new ArrayList<>(); list.forEach(x -> { if (x == 2) extra.add(99); }); list.addAll(extra);

How to avoid it next time

Collect changes in a separate collection and apply them after the iteration.

Want the background? Read ConcurrentModificationException in the Java concepts library.

About modifying while iterating

Collections detect structural changes made during iteration and throw ConcurrentModificationException, but only some of the time, and not at all for certain patterns. Removing in a loop is a classic way to skip elements or crash.

In code review: Any call to add or remove on the collection being looped over deserves suspicion. Use Iterator.remove, removeIf, or build a new collection.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #22#24 โ†’

Frequently asked questions

What is the bug in "Adding while forEach is running"?

ArrayList.forEach checks for modification after the loop and throws ConcurrentModificationException when the lambda changes the list. Streams and forEach are not safe places to mutate their own source. The faulty line is line 6: list.forEach(x -> { if (x == 2) list.add(99); });

How do I fix it?

Replace it with: List extra = new ArrayList<>(); list.forEach(x -> { if (x == 2) extra.add(99); }); list.addAll(extra);. Collect changes in a separate collection and apply them after the iteration.

How do I catch modifying while iterating in code review?

Any call to add or remove on the collection being looped over deserves suspicion. Use Iterator.remove, removeIf, or build a new collection.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need