Sub topic 18
Parallel Streams: When They Help and When They Hurt
A normal stream handles its elements one at a time, on one thread. A thread is one path of work that your computer runs. A parallel stream splits the elements into chunks and processes those chunks on several threads at once. On a computer with several CPU cores, this can finish some jobs faster.
Making a Stream Parallel
You can get a parallel stream in two ways:
- Call
parallelStream()on a collection instead ofstream(). - Call
.parallel()on a stream you already have.
import java.util.List;
import java.util.stream.IntStream;
public class ParallelExample {
public static void main(String[] args) {
long sum = IntStream.rangeClosed(1, 1_000_000)
.parallel()
.asLongStream()
.sum();
System.out.println(sum); // 500000500000
List<String> names = List.of("alice", "bob", "carol");
long longNames = names.parallelStream()
.filter(n -> n.length() > 3)
.count();
System.out.println(longNames); // 2
}
}The answers are the same as with a sequential stream. Only the way the work gets done changes.
When Parallel Helps
Parallel streams tend to help when all of these are true:
- There are many elements, often tens of thousands or more.
- Each element takes real work to process.
- The source splits easily. Arrays,
ArrayList, andIntStream.rangesplit well.LinkedListandStream.iteratesplit poorly. - The operations do not depend on order or on shared state.
When Parallel Hurts
Splitting the work, starting threads, and combining the results all take time. For a small list, that overhead costs more than it saves, so the parallel version can run slower.
Order also changes. forEach on a parallel stream prints elements in an unpredictable order. Use forEachOrdered if you need the original order.
The worst problem is shared mutable state. Mutable state is data that the code changes. If several threads add to the same plain ArrayList, elements can go missing or the program can crash.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SafeCollect {
public static void main(String[] args) {
// Safe: let the stream build the list itself
List<Integer> evens = IntStream.rangeClosed(1, 10)
.parallel()
.filter(n -> n % 2 == 0)
.boxed()
.collect(Collectors.toList());
System.out.println(evens); // [2, 4, 6, 8, 10]
}
}collect gives each thread its own list and merges the lists safely. The result also keeps the source order.
A Simple Rule
Start with a sequential stream. Switch to parallel only when you have a large amount of data and have measured that the parallel version is faster.
Exercise
You have a list of 20 short strings and want to count how many start with "a". Should you use parallelStream()? Why?
Show answer
No. With only 20 cheap elements, the cost of splitting the work and combining the results is larger than any time saved. A sequential stream will likely be faster and is simpler.
Exercise
Why is calling list.add(x) on a shared ArrayList inside a parallel forEach a bug, and what should you use instead?
Show answer
ArrayList is not safe for several threads to change at once, so elements can be lost or an exception can be thrown. Use collect(Collectors.toList()) or toList() so the stream builds the list safely.