Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

This code sometimes throws ConcurrentModificationException or loses elements:

Java
List<String> out = new ArrayList<>();
items.parallelStream().filter(this::valid).forEach(out::add);

Explain and fix.

ArrayList is not thread-safe, and a parallel forEach calls out::add from several fork-join threads at once, so two threads can write the same slot, leave a null gap, or race through a resize and throw ArrayIndexOutOfBoundsException; other code touching the list at the same time can see a ConcurrentModificationException. The fix is to let the stream build the list: items.parallelStream().filter(this::valid).toList(), or collect(Collectors.toList()), which gives each thread its own container and merges them safely. Mutating shared state from stream lambdas breaks the stream contract, and forEach on a parallel stream does not keep encounter order either.

Why this question is asked

This bug is a favourite in interviews because it fails only sometimes, only with parallel streams, and only with enough data, which is exactly how it escapes code review and tests. Understanding it requires knowing a little about what ArrayList.add does inside and how a parallel stream divides work between threads. In this answer, we will recap the two pieces, reproduce the failure, look inside add to see the race, fix it properly, and finish with the general rule about side effects and ordering in streams.

1A Quick Recap of the Two Pieces

A parallel stream splits its source into chunks and processes them at the same time on threads from the fork-join common pool, plus the calling thread. With forEach, each thread calls the action for the elements in its own chunks. So out::add is called by, say, eight threads at the same moment.

ArrayList keeps its elements in an internal array and a size field. It is not thread-safe, which means its methods assume only one thread uses the list at a time. Its documentation says so, and recommends external synchronisation when several threads modify it. Nothing in this code provides that.

2Reproducing the Failure

The problem shows up reliably with a large enough input. Here 100,000 numbers are filtered for even values, so the correct answer is always 50,000 elements.

Java
List<Integer> items = IntStream.range(0, 100_000).boxed().toList();
for (int run = 0; run < 3; run++) {
List<Integer> out = new ArrayList<>();
try {
items.parallelStream().filter(i -> i % 2 == 0).forEach(out::add);
System.out.println(out.size() + " elements, nulls: " + out.contains(null));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("failed: " + e);
}
}
// for example:
// 49816 elements, nulls: true
// failed: java.lang.ArrayIndexOutOfBoundsException: Index 24631 out of bounds for length 24630
// 49903 elements, nulls: false

The exact numbers change on every run and every machine; that unpredictability is the signature of a data race. The sequential version, stream() instead of parallelStream(), prints 50000 every time.

3Why ArrayList Breaks: Inside add

Simplified, ArrayList.add does three things: check whether the internal array has room and grow it if not, write the element at position size, and increment size. None of these is atomic with the others, and no lock protects them.

Java
// simplified ArrayList.add
if (size == elementData.length) elementData = grow(); // copy into a bigger array
elementData[size] = e; // write at the current end
size = size + 1; // move the end
Step throughTwo threads add to the same ArrayList
Worker 1ArrayList (size 500)Worker 2
read size: 500
read size: 500
write A at slot 500
write B at slot 500 (A is lost)
size = 501
size = 502 (slot 501 stays null)

6 messages in order. Play them, or step through them one at a time.

Without a lock, the read, the write and the increment interleave, losing elements and leaving gaps.

Now picture two threads. Both read size as 500 at the same time. Both write their element into slot 500, so one element overwrites the other and is lost. Then both increment size, which ends at 502, leaving slot 501 empty, which is the null we saw. Or one thread decides there is room, the other fills the last slot and the first then writes past the end of the array: ArrayIndexOutOfBoundsException. Or one thread grows the array by copying it while another writes into the old array, and that write disappears.

As for ConcurrentModificationException, it comes from ArrayList's fail-fast iterators: if any code iterates over the list, for example logging it or copying it, while adds are still happening, the iterator notices that the modification count changed and throws. Which of these symptoms we see depends on timing, which is why the bug looks random.

4The Fix: Let the Stream Build the List

The right fix is not to protect the shared list but to stop sharing it. Streams have a built-in way to produce a collection from a parallel computation, and it is designed for exactly this.

Java
List<String> out = items.parallelStream()
.filter(this::valid)
.toList(); // Java 16+: unmodifiable, in encounter order
List<String> mutable = items.parallelStream()
.filter(this::valid)
.collect(Collectors.toCollection(ArrayList::new)); // if the caller must modify it
Ways to gather results from a parallel stream
ApproachThread-safeKeeps encounter orderContention
forEach(out::add) on ArrayListnononone, but corrupt
forEach on synchronizedListyesnoevery add takes a lock
forEachOrdered(out::add)yesyeseffectively sequential
collect(Collectors.toList())yesyesnone: per-thread containers
toList()yesyesnone, unmodifiable result
Let the stream own the containers; do not share one from outside.

collect and toList perform a mutable reduction safely. Each thread accumulates into its own private container, so there is no sharing during the work, and the containers are merged in encounter order when the chunks are combined. The result is correct, has every valid element exactly once, and keeps the original order of items. toList returns an unmodifiable list; collect(Collectors.toList()) or toCollection(ArrayList::new) return lists we can change.

Wrapping the list with Collections.synchronizedList also stops the corruption, but it is a worse fix. Every add now takes a lock, so the threads queue for it and much of the parallel benefit disappears, and the order of the result is still random. It is also worth asking whether this stream should be parallel at all: filtering a list with a cheap valid() check is rarely enough work to beat a sequential stream.

5The Rule Behind It: No Side Effects on Shared State

The stream documentation says behavioural parameters, our lambdas, should in general be free of side effects, and in particular must not modify shared state without synchronisation. Adding to an outside list from forEach is exactly such a side effect. In a sequential stream it happens to work, which is why the code was written, but the contract is the same for both, and the same code becomes wrong the moment someone adds parallel.

There is a second, quieter problem. Even with a thread-safe list, forEach on a parallel stream runs the action in whatever order the threads reach the elements, so the result order differs from the source. forEachOrdered preserves order but processes the elements one at a time in order, which removes most of the parallel benefit. Collecting gives both safety and order without that cost.

6Follow-up questions

Why does the sequential version always work?

Because only one thread calls add, so the read, write and increment never interleave. The code is still relying on a side effect, which the stream contract discourages, but there is no race. The bug was always latent; parallel only exposed it.

Would a ConcurrentLinkedQueue or CopyOnWriteArrayList be acceptable?

ConcurrentLinkedQueue is thread-safe and cheap to add to, but it still loses encounter order. CopyOnWriteArrayList copies the whole array on every add, which is very slow for many elements. Both are worse than collect, which is safe, ordered and contention-free.

How would you catch this in review or tests?

In review, any forEach or peek whose lambda mutates something declared outside the stream is a red flag, and static analysis can flag forEach on parallel streams. In tests, running the method on a large input many times and asserting the exact expected size and contents usually exposes the race quickly.

7Conclusion

In this answer, we saw that a parallel forEach calls ArrayList.add from several threads at once, and because add reads the size, writes a slot and increments the size without any lock, elements are lost, nulls appear, resizes throw ArrayIndexOutOfBoundsException, and concurrent iteration can throw ConcurrentModificationException. The fix is to let the stream build the result with toList() or collect, which use per-thread containers and keep encounter order. The underlying rule is that stream lambdas must not mutate shared state, and forEach on a parallel stream does not preserve order.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that ArrayList is not thread-safe and a parallel forEach calls out::add from several fork-join threads at the same time. Inside, add checks capacity and maybe grows the array, writes the element at index size, and then increments size, with no lock.

Then, if they want more

So two threads can both read the same size and write to the same slot, losing one element, then both increment size, leaving a null gap. If one grows the array while another writes, you get ArrayIndexOutOfBoundsException, and if anything iterates the list while adds are happening, the fail-fast iterator throws ConcurrentModificationException.

The results change on every run, which is typical of a data race. The fix is not to share the list at all: items.parallelStream().filter(this::valid).toList(), or collect(Collectors.toList()) if I need a modifiable list. Collect gives each thread its own container and merges them in encounter order, so it is safe and the order matches the source.

A synchronizedList would stop the corruption but adds lock contention and still loses order. More generally, stream lambdas should not mutate shared state; it breaks the stream contract and only works by luck when the stream is sequential. And forEach on a parallel stream never keeps encounter order anyway. I would also question whether this stream needs to be parallel at all.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code sometimes throws ConcurrentModificationException or loses elements:": https://scrivio-interview-library.netlify.app/java/streams/496befa6af/