Video in progress

Strong Middle 🌊 Streams and lambdas

What happens if you add results to an ArrayList with forEach in a parallel stream? How do you fix the code?

List<Long> ids = new ArrayList<>();
orders.parallelStream()
      .filter(Order::paid)
      .map(Order::id)
      .forEach(ids::add);
System.out.println(ids.size());

ArrayList is not thread-safe: if several ForkJoin threads call add at the same time, elements get lost, nulls appear, or an ArrayIndexOutOfBoundsException is thrown. The right way is collect/toList, which give each chunk its own container and merge them at the end.

📖 Answer

In a test with 1000 elements this code often works correctly, but in prod with 200 thousand it prints a different number on every run. Sometimes there's an exception too, because size++ and growing the array inside ArrayList.add are not atomic.

"Fixing" it with Collections.synchronizedList or CopyOnWriteArrayList is a bad solution. The first makes all threads queue on a single lock, and nothing is left of the parallelism benefit. The second copies the whole array on every add. Order also gets broken on top of that.

The right way:

List<Long> ids = orders.parallelStream()
        .filter(Order::paid)
        .map(Order::id)
        .toList();

This is how collect works inside: each chunk (a piece of the Spliterator) has its own container, the threads don't touch each other, and at the end the combiner merges them. This is called mutable reduction, and it is both safe and preserves the source order.

A good way to check this is jcstress, or simply running the test 100 times with a large data set. A test that passed once proves nothing here.