Sub topic 18
Parallel Streams: When They Help and When They Hurt
All the streams so far in this tutorial have been sequential. A sequential stream handles one element at a time, in order, on one thread. A thread is a single path of work that your program runs. Most computers today have several cores. A core is a part of the processor that can run one thread at a time. A parallel stream splits its work across several cores so that parts of the job run simultaneously.
That sounds like free speed, but it isn't free. This chapter shows how parallel streams work, when they are faster, and the mistakes that make them slower or wrong.
How a Parallel Stream Works
You can turn any stream into a parallel one in two ways:
- Call
parallelStream()on a collection instead ofstream(). - Call
.parallel()on a stream you already have.
Behind the scenes, Java uses the common fork/join pool. A thread pool is a group of threads that is ready to do work. The fork/join pool splits the source into chunks. Each thread processes its own chunk through the pipeline. Then Java combines the partial results into one final answer.
The split and combine steps cost time. A parallel stream only wins when the work saved is bigger than that cost.
A First Parallel Stream
This program sums the numbers from 1 to 10 million twice, once in order and once in parallel. Both give the same answer.
import java.util.stream.LongStream;
public class ParallelSumExample {
public static void main(String[] args) {
long sequential = LongStream.rangeClosed(1, 10_000_000).sum();
long parallel = LongStream.rangeClosed(1, 10_000_000)
.parallel()
.sum();
System.out.println(sequential); // 50000005000000
System.out.println(parallel); // 50000005000000
System.out.println("Cores: " + Runtime.getRuntime().availableProcessors());
}
}This is a good case for parallel work. LongStream.rangeClosed is easy to split in half. The values are primitive longs, so there is no boxing. Summing is simple and the order of the additions doesn't change the result.
Mistake 1: Changing Shared State
The chapter on stream pitfalls warned against lambdas that change outside variables. In a parallel stream that mistake becomes a real bug. Here, many threads add to one ArrayList at the same time. ArrayList is not thread-safe. Thread-safe means it is safe to use from many threads at once.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SharedStateExample {
public static void main(String[] args) {
List<Integer> unsafe = new ArrayList<>();
try {
IntStream.range(0, 10_000)
.parallel()
.forEach(unsafe::add);
System.out.println("Unsafe size: " + unsafe.size()); // often less than 10000
} catch (RuntimeException e) {
System.out.println("Unsafe version crashed: " + e);
}
List<Integer> safe = IntStream.range(0, 10_000)
.parallel()
.boxed()
.collect(Collectors.toList());
System.out.println("Safe size: " + safe.size()); // 10000
}
}The unsafe version can lose elements, or it can crash. Each run may behave differently. The safe version uses collect. A collector gives each thread its own container and then merges the containers safely.
Mistake 2: Expecting Order from forEach
In a parallel stream, forEach runs the action as soon as each thread is ready. The output order is unpredictable. If you need the original order, use forEachOrdered.
import java.util.List;
public class OrderExample {
public static void main(String[] args) {
List<String> letters = List.of("a", "b", "c", "d", "e");
letters.parallelStream()
.forEach(s -> System.out.print(s + " "));
System.out.println(" <- forEach, order may change");
letters.parallelStream()
.forEachOrdered(s -> System.out.print(s + " "));
System.out.println(" <- forEachOrdered: a b c d e");
}
}Most operations still keep their order. For example, collect(Collectors.toList()) on an ordered source returns elements in the original order. Keeping order can slow a parallel stream down, though. If you need any match and not the first one, use findAny instead of findFirst. findAny lets each thread return whatever it finds first.
Mistake 3: A Wrong Identity in reduce
The reduce chapter said the identity value must not change a result. For addition, the identity is 0, because x + 0 equals x. In a sequential stream, a wrong identity is used once. In a parallel stream, it is used once per chunk.
import java.util.List;
public class IdentityExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sequential = numbers.stream().reduce(10, Integer::sum);
System.out.println(sequential); // 25
int parallel = numbers.parallelStream().reduce(10, Integer::sum);
System.out.println(parallel); // often more than 25
int correct = numbers.parallelStream().reduce(0, Integer::sum) + 10;
System.out.println(correct); // 25
}
}The function must also be associative. Associative means the grouping doesn't matter: (a + b) + c equals a + (b + c). Addition and max are associative. Subtraction is not, so reduce(0, (a, b) -> a - b) gives different answers in parallel.
When Parallel Streams Help
Parallel streams tend to be faster when most of these are true:
| Factor | Good for parallel | Bad for parallel |
|---|---|---|
| Amount of data | Large, such as hundreds of thousands of elements | Small, such as a few hundred elements |
| Work per element | Heavy, such as math or parsing | Tiny, such as adding 1 |
| Source | `ArrayList`, arrays, `IntStream.range` | `LinkedList`, `Stream.iterate`, I/O lines |
| Operations | `map`, `filter`, `sum`, `count` | `sorted`, `distinct`, `limit` on ordered data |
| Element type | Primitive streams | Boxed values like `Integer` |
| Side effects | None | Writes to shared variables |
An array is easy to split because Java can jump straight to its middle. A LinkedList has to be walked one node at a time to find the middle. Stream.iterate has the same problem, because each value depends on the one before it.
When Parallel Streams Hurt
- Small data. Splitting and combining take longer than the work itself.
- Blocking work. Blocking means a thread waits, for example for a web request or a file. The common pool has about one thread per core. If those threads wait, the pool stalls. Other parallel streams in the same program stall too, because they share the pool.
- Order-heavy pipelines.
limit,findFirst, andsortedmust coordinate across threads to respect order. - Code inside a web server. The server already uses every core for different requests. A parallel stream there competes for the same cores.
A Simple Checklist
- Is the data large and is each step costly? If not, stay sequential.
- Is the source easy to split? Prefer arrays,
ArrayList, and ranges. - Are the lambdas free of side effects?
- Is the
reduceidentity a true identity, and is the function associative? - Did you measure, and is it actually faster?
If every answer is yes, a parallel stream is a reasonable choice.
Exercise
A teammate writes int total = list.parallelStream().reduce(1, Integer::sum); to add up a list and then add 1. Why can this give the wrong answer, and how should it be fixed?
Show answer
In a parallel stream, each chunk starts from the identity value, so the extra 1 is added once per chunk, not once in total. The identity for addition must be 0. Write list.parallelStream().reduce(0, Integer::sum) + 1, or list.parallelStream().mapToInt(Integer::intValue).sum() + 1.
Exercise
You need to fetch 50 web pages and count the words on each. Is a parallel stream a good tool for this? Explain.
Show answer
Usually not. Fetching pages is blocking work, so the threads mostly wait for the network. The common fork/join pool has only about one thread per core, so waiting threads stall it and slow other parallel streams in the program. A separate thread pool (an ExecutorService) or asynchronous HTTP calls suit this job better.
Exercise
Which of these is the best candidate for a parallel stream, and why? (a) Summing 200 Integers in a LinkedList. (b) Computing an expensive score for each of 2 million elements in an array and finding the maximum. (c) Printing 1,000 lines of a file in order.
Show answer
(b). It has a large amount of data, heavy work per element, a source that is easy to split, and a max reduction where the order of the steps doesn't affect the answer. (a) is too small, uses boxed values, and has a source that is hard to split. (c) needs strict order and does I/O.