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.
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());