Q 61
Hard
How do Parallel Streams work internally and what are the risks of using them?
Answer
Parallel streams partition stream elements using Spliterators and process chunks concurrently across CPU cores using the shared ForkJoinPool.commonPool(). Risks include: blocking I/O starving the shared pool, race conditions on non-thread-safe state, and overhead exceeding benefits on small datasets.
Explanation
Parallel streams should only be used on CPU-bound computations with large datasets ($N \times Q > 10,000$) where operations are completely stateless and associative.
Code Example
Java
// Fast for CPU-bound computations:
long count = largeNumberList.parallelStream()
.filter(PrimeChecker::isPrime)
.count();
Reference:
Java Functional Programming & Streams API