Quick revision
The short answer
ArrayList is not thread-safe, and a parallel stream runs forEach on several ForkJoinPool threads at once, so their add calls race: two threads write the same slot and one result is lost, or one thread grows the internal array while another writes past the old end, which throws ArrayIndexOutOfBoundsException. The fix is to let the stream collect with .toList(), which gathers results per thread and combines them safely and in encounter order. In reviews I also look for pipelines that modify their own source (ConcurrentModificationException), logic placed in peek, which may not run at all, for example with count() on a sized source, and blocking I/O on the common pool.
What to remember
In this answer, we saw that forEach(results::add) on a parallel stream calls ArrayList.add from several ForkJoinPool threads, so writes to the same slot are lost, nulls appear, and a race with the internal resize can throw ArrayIndexOutOfBoundsException. Replacing it with toList() lets each thread collect into its own container and combines them safely and in encounter order. In reviews we also look for modifications of the source inside a pipeline, logic hidden in peek, which may be skipped, as with count() on a sized source, and blocking I/O on the shared common pool.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
ArrayList is not thread-safe, and a parallel stream runs forEach on several ForkJoinPool threads at once, so their add calls race: two threads write the same slot and one result is lost, or one thread grows the internal array while another writes past the old end, which throws ArrayIndexOutOfBoundsException. The fix is to let the stream collect with .toList(), which gathers results per thread and combines them safely and in encounter order. In reviews I also look for pipelines that modify their own source (ConcurrentModificationException), logic placed in peek, which may not run at all, for example with count() on a sized source, and blocking I/O on the common pool.
Why this question is asked
This bug is a favourite in interviews because it looks harmless: the sequential version of the same code works perfectly, and adding parallelStream() seems like a free speed-up. The failure is intermittent, which makes it hard to reproduce, and it can silently drop data, which is worse than crashing. In this answer, we will recap how a parallel stream executes, see exactly how ArrayList.add loses elements and throws, fix it with toList(), talk about ordering, and then go through the other side-effect bugs worth catching in code review.
1A Quick Recap of How a Parallel Stream Runs
A parallel stream splits its source into chunks and processes them on several threads of the common ForkJoinPool, a shared pool with roughly one thread per CPU core, plus the calling thread. Each operation in the pipeline, here map(this::price) and then forEach(results::add), runs on whichever thread holds the chunk.
The Stream API expects the functions we pass to be non-interfering, meaning they do not modify the source, and preferably stateless, meaning their result does not depend on or change shared state. forEach(results::add) breaks the second rule: every thread calls add on the same ArrayList, and ArrayList has no synchronization at all.
2How ArrayList.add Loses Elements and Throws
Inside, ArrayList keeps an Object[] elementData and an int size. Simplified, add(e) checks whether size has reached the array's length, grows the array if so, then stores e at elementData[size] and increments size. Those are several separate steps, and two threads can interleave them.
6 messages in order. Play them, or step through them one at a time.
Both adds report success, but only resultB is in the list.
Lost elements happen when two threads read the same size, say 41, both store their result in slot 41, one overwriting the other, and both write size = 42. One result is gone, with no error. Nulls appear when the size increments get out of step with the writes, so a slot inside the size is never filled. The exception happens around a resize: thread A sees there is room and is about to write at index size, while thread B grows the array and increments size, or A reads an increased size before the bigger array is visible, and writes past the end of the array it has. ConcurrentModificationException is rare here, since nobody iterates the list during the adds.
None of this is guaranteed to happen on any particular run, which is the real danger. With small inputs or a lightly loaded machine, the race window is small and tests pass. In production, under load, a fraction of the orders silently disappears from the result.
3The Fix: Let the Stream Collect
Instead of pushing results into a shared list from inside the pipeline, we let the stream build the list. Stream.toList(), added in Java 16, and collect(Collectors.toList()) both know how to collect in parallel safely.
Under the hood, each thread fills its own private container for its chunk, and the stream combines the containers when chunks finish, so no two threads ever touch the same list. That is the safe-by-design part. toList() returns an unmodifiable list, so any later add throws UnsupportedOperationException; if the code needs a mutable list, toCollection(ArrayList::new) gives one.
It is tempting to fix the bug with Collections.synchronizedList or a CopyOnWriteArrayList. Both stop the corruption, but every add then fights for one lock, or copies the whole array, which throws away much of the benefit of running in parallel, and the order is still random. Collecting is faster and simpler.
4Order Matters Too
Even with a thread-safe list, forEach on a parallel stream does not respect encounter order, the order of the source. It runs the action on each element as soon as its chunk is processed, so the results arrive in a different order on every run. If the results must line up with the orders, for example to zip them back together by index, that is a second bug hiding behind the first.
toList() and collect keep encounter order for an ordered source like a List, because the stream combines the per-thread containers in the right order. If we really need a side effect in order, forEachOrdered does that, at the cost of some parallelism, since each element must wait for the ones before it.
5Other Side-Effect Bugs Worth Catching in Review
The first is modifying the source inside the pipeline, for example orders.stream().filter(o -> o.isCancelled()).forEach(orders::remove). The stream is iterating over orders while the code removes from it, which typically throws ConcurrentModificationException for an ArrayList source, or behaves unpredictably for other collections. The fix is orders.removeIf(Order::isCancelled), or collecting the items to remove first.
The second is relying on peek for logic. peek exists for debugging, and the stream is allowed to skip it. Since Java 9, count() can compute the size directly from a sized source without running the pipeline at all, so List.of(1, 2, 3).stream().peek(audit::record).count() returns 3 and never calls audit.record. Similarly, a short-circuiting operation like findFirst stops calling peek early. Anything that must happen belongs in map or in a real terminal operation.
The third is blocking I/O in a parallel stream, such as calling a remote pricing API inside map(this::price). Parallel streams run on the common ForkJoinPool, which has about as many threads as cores and is shared by every parallel stream and by CompletableFuture's default async methods in the JVM. Blocking those few threads on network calls stalls everything else that uses the pool. For I/O-bound work, an executor built for it, such as virtual threads with a concurrency limit, is the right tool.
6Follow-up questions
When is a parallel stream a good idea in a web service?
Rarely inside request handling. A web server already runs many requests in parallel, so a parallel stream mostly competes with other requests for the same cores and adds splitting overhead. It pays off for CPU-bound work on a large amount of data, tens of thousands of elements or more with real per-element cost, that runs rarely or in a batch job, and only when measurements show a gain. It is a poor fit for small collections, blocking I/O, or code with locks.
Would Collections.synchronizedList fix the bug?
It fixes the corruption, because each add takes a lock, but it does not fix the ordering, and every add now contends for one lock, so much of the parallel speed-up disappears. Collecting with toList() is correct, ordered and faster, so it is the fix I would make.
Why does the sequential version never fail?
Because in a sequential stream every add runs on the calling thread, one after another, so the steps of add can never interleave. The code is only correct by accident of being single-threaded, which is why adding parallelStream() exposes it.
7Conclusion
In this answer, we saw that forEach(results::add) on a parallel stream calls ArrayList.add from several ForkJoinPool threads, so writes to the same slot are lost, nulls appear, and a race with the internal resize can throw ArrayIndexOutOfBoundsException. Replacing it with toList() lets each thread collect into its own container and combines them safely and in encounter order. In reviews we also look for modifications of the source inside a pipeline, logic hidden in peek, which may be skipped, as with count() on a sized source, and blocking I/O on the shared common pool.
Open with
The problem is that ArrayList is not thread-safe and the parallel stream calls add from several ForkJoinPool threads at once. Add is several steps: check the capacity, maybe grow the array, write at index size, increment size.
Then, if they want more
If two threads read the same size, they write into the same slot, one result is lost, and both report success, so I get fewer results than orders. If one thread grows the array while another is writing, the writer can use an index past the end of the array it holds, which is the ArrayIndexOutOfBoundsException.
It only fails sometimes because it depends on timing. The fix is not a synchronized list, it is to stop mutating shared state and let the stream collect: orders.parallelStream, map price, toList. Each thread collects its own chunk and the stream combines them safely, and for a list source the result is in the original order, which forEach never guaranteed.
If the caller needs to modify the list, I would use toCollection ArrayList::new, since toList is unmodifiable. Two other side-effect bugs I look for in reviews: modifying the source collection inside the pipeline, like removing from the list you are streaming, which gives ConcurrentModificationException, where removeIf is the fix.
And logic inside peek, which the stream may skip entirely, for example count on a sized list does not run the pipeline since Java 9. I also flag blocking calls inside parallel streams, because they tie up the common pool that the whole JVM shares.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16, Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 returns fewer results than expected and occasionally throws...": https://scrivio-interview-library.netlify.app/java/coding-problems/b9b8895737/