Parallel Streams
TL;DR
- Parallel Streams split a stream into multiple chunks and process them concurrently using multiple threads.
- You can create one by calling
.parallelStream()on a collection, or.parallel()on an existing stream. - Under the hood, it uses the common ForkJoinPool.
Concept
Modern CPUs have multiple cores. Standard streams execute sequentially on a single thread. If you are processing millions of records, a single thread leaves your other CPU cores idle.
By simply changing .stream() to .parallelStream(), Java automatically splits the data, creates multiple background threads, processes the chunks in parallel, and merges the results back together at the end. It takes the complex burden of multithreading away from the developer.
Examples
import java.util.ArrayList;
import java.util.List;
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 1_000_000; i++) {
numbers.add(i);
}
long startTime = System.currentTimeMillis();
// Using a sequential stream
long count1 = numbers.stream()
.filter(n -> n % 2 == 0)
.count();
System.out.println("Sequential Time: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
// Using a parallel stream
long count2 = numbers.parallelStream() // Only change is here!
.filter(n -> n % 2 == 0)
.count();
System.out.println("Parallel Time: " + (System.currentTimeMillis() - startTime) + "ms");
}
}
Interview Questions
Q: Should you always use Parallel Streams?
A: No. Parallel streams have significant overhead (splitting data, managing threads, merging results).
You should only use parallel streams if:
- You have a massive amount of data (e.g., > 10,000 items).
- The operations are computationally expensive (CPU-bound).
- The data structure is easily splittable (like an
ArrayList. ALinkedListsplits terribly).
If you use a parallel stream on 100 items, it will almost certainly be slower than a sequential stream due to thread overhead.
Q: What happens if you perform a network or database call inside a Parallel Stream?
A: This is extremely dangerous. Parallel streams share the global ForkJoinPool with the rest of the JVM. If you make a blocking network call inside a parallel stream map(), you will block all the threads in the common pool, potentially grinding the entire JVM application to a halt. Parallel streams are designed for CPU-bound tasks, not I/O-bound tasks.