Mastery
Mastery/Java/D. Streams & functional interfaces
T2 · intermediate depth

Parallel streams: the common ForkJoinPool, when it helps, ordering pitfalls

.parallelStream() (or .parallel()) splits work across the shared common ForkJoinPool, sized to the machine's core count -- real speedup for CPU-heavy work over large data. The tradeoff: any ordering guarantee disappears unless you explicitly force it back with forEachOrdered, and for small/cheap workloads the splitting/merging overhead can make parallel slower than sequential.

java
import java.util.*;
import java.util.stream.*;

List<Integer> nums = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());

System.out.print("sequential forEach:            ");
nums.forEach(n -> System.out.print(n + " "));
System.out.println();

System.out.print("parallel forEach (unordered):  ");
nums.parallelStream().forEach(n -> System.out.print(n + " "));
System.out.println();

System.out.print("parallel forEachOrdered:       ");
nums.parallelStream().forEachOrdered(n -> System.out.print(n + " "));
System.out.println();

System.out.println("common ForkJoinPool parallelism on this machine: " + Runtime.getRuntime().availableProcessors());

Interview angle

A good "do you actually understand this or just use it" question: "when would .parallelStream() make code slower?" Strong candidates mention small collections (splitting/merging overhead dominates), I/O-bound work (parallel streams are for CPU-bound work; blocking I/O ties up common-pool threads other parallel work needs), and stateful/order-dependent operations — showing they've thought about the cost side, not just the API.

In the industry

Parallel streams are a genuinely common performance-review "why is this slower than expected" finding — they get reached for reflexively as a speed boost and then blamed when they don't help (or actively hurt) on small or I/O-bound workloads. They share the same common ForkJoinPool as everything else using parallel streams JVM-wide, which is a real, sometimes-surprising source of contention in larger applications that use them in more than one place without realizing the pool is shared.