Parallel Streams: Performance and Pitfalls
Enable parallel streams, understand the common thread pool, and avoid shared mutable state bugs.
Enabling Parallel Streams
Call .parallel() on any stream or use Collection.parallelStream(). The stream operations run on the common ForkJoinPool (default: CPU cores - 1 threads).
long count = list.parallelStream()
.filter(n -> n % 2 == 0)
.count();
System.out.println(count);When Parallel Pays Off
Parallel streams are worth it when: the dataset is large (100,000+ elements), each element operation is computationally expensive, and the pipeline is stateless and order-independent.
// Good candidate: CPU-heavy computation on large dataset
long sum = LongStream.rangeClosed(1, 10_000_000)
.parallel()
.filter(n -> isPrime(n))
.sum();
System.out.println(sum);All lessons in this course
- flatMap for Nested Collections
- Parallel Streams: Performance and Pitfalls
- Spliterator: Splitting for Parallelism
- Infinite Streams with iterate and generate