When parallel streams help and hurt
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A parallel stream is faster only when the work saved by using several cores is bigger than the extra work of splitting the data, handing chunks to threads and merging the results. For most everyday lists that is not true, so the sequential stream is the normal choice and parallel is a tool you prove with a measurement.
What makes parallel worth it
Parallel work has fixed costs: the source must be split, each chunk must be handed to a thread, and the partial results must be merged. For a list of 50 marks these costs are far bigger than the work itself, and the parallel version is slower.
A useful rule of thumb is N × Q: the number of elements times the work per element. Adding 1000 numbers is a small N and a tiny Q. Checking 2 million numbers for being prime is a big N and a real Q, and there parallel can be several times faster.
The merge must also be cheap. Adding two partial sums or keeping the larger of two maxima is instant. Merging two big maps from groupingBy, or two lists in order, costs more. Steps that care about order, such as sorted, distinct, limit and findFirst, make threads wait for each other. Boxing into Integer objects adds memory traffic that can eat the gain.
- Large data: usually tens of thousands of elements or more.
- Real work per element: a calculation, not just a field read.
- Cheap merging:
sum,count,max,min,anyMatch. - A splittable source: an array, an
ArrayListor anIntStream.range.
ArrayList and arrays split well; LinkedList and iterate do not
Splitting is fast when the source knows its size and can jump to any position. An array, an ArrayList and IntStream.range can be cut exactly in half in one step, then in quarters, and so on.
Example 1 · How well each source splits
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Spliterator;import java.util.stream.IntStream;import java.util.stream.Stream;
public class SplitDemo { static String size(long n) { return n == Long.MAX_VALUE ? "unknown" : String.valueOf(n); }
static void firstSplit(String name, Spliterator<?> part) { long before = part.estimateSize(); Spliterator<?> other = part.trySplit(); String after = other == null ? "cannot split" : size(other.estimateSize()) + " + " + size(part.estimateSize()); System.out.println(name + ": " + size(before) + " -> " + after); }
public static void main(String[] args) { List<Integer> arrayList = new ArrayList<>(IntStream.range(0, 100_000).boxed().toList()); List<Integer> linkedList = new LinkedList<>(arrayList);
firstSplit("int[] ", Arrays.spliterator(new int[100_000])); firstSplit("ArrayList ", arrayList.spliterator()); firstSplit("IntStream.range", IntStream.range(0, 100_000).spliterator()); firstSplit("LinkedList ", linkedList.spliterator()); firstSplit("Stream.iterate ", Stream.iterate(0, i -> i + 1).limit(100_000).spliterator()); }}int[] : 100000 -> 50000 + 50000 ArrayList : 100000 -> 50000 + 50000 IntStream.range: 100000 -> 50000 + 50000 LinkedList : 100000 -> 1024 + 98976 Stream.iterate : unknown -> cannot split
What this code does
- A
Spliteratoris the object a parallel stream uses to cut its source;trySplit()hands back the first part and keeps the rest. Arrays,ArrayListand ranges split into two equal halves at once. - The
LinkedListgives away only a batch of 1024 nodes and keeps 98976 for one thread.iteratewithlimitcannot be split at all, because each value needs the previous one.
Example 2 · Same data, ArrayList versus LinkedList
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.stream.IntStream;
public class SourceTimingDemo { static void time(String label, List<Integer> list) { for (int run = 1; run <= 3; run++) { long start = System.nanoTime(); long total = list.parallelStream().mapToLong(i -> (long) i * i % 1_000_003).sum(); double ms = (System.nanoTime() - start) / 1_000_000.0; System.out.printf("%s run %d: %7.2f ms (total %d)%n", label, run, ms, total); } }
public static void main(String[] args) { List<Integer> arrayList = new ArrayList<>(IntStream.range(0, 3_000_000).boxed().toList()); List<Integer> linkedList = new LinkedList<>(arrayList);
time("ArrayList parallel", arrayList); time("LinkedList parallel", linkedList); time("LinkedList copied ", new ArrayList<>(linkedList)); }}ArrayList parallel run 1: 62.09 ms (total 1499692498779) ArrayList parallel run 2: 5.21 ms (total 1499692498779) ArrayList parallel run 3: 4.61 ms (total 1499692498779) LinkedList parallel run 1: 221.84 ms (total 1499692498779) LinkedList parallel run 2: 81.11 ms (total 1499692498779) LinkedList parallel run 3: 43.75 ms (total 1499692498779) LinkedList copied run 1: 4.53 ms (total 1499692498779) LinkedList copied run 2: 4.39 ms (total 1499692498779) LinkedList copied run 3: 3.96 ms (total 1499692498779)
What this code does
- The same 3 million numbers and the same work run several times slower from a
LinkedList, because splitting means walking the nodes and the threads get uneven chunks. - Copying the
LinkedListinto anArrayListcosts one pass, and then the parallel stream splits evenly again. Each total matches, so only the speed changes.
HashSet and HashMap split fairly well too, because they are built on an array inside. A LinkedList can only be walked node by node from the start. To split it, Java must walk the first 1024 nodes and copy them into an array, and the rest stays as one big piece. The threads get badly uneven work. Stream.iterate is worse: each value needs the previous one, so it cannot be split at all, and one thread must create every value in order.
If your data sits in a LinkedList or comes from iterate, copy it into an ArrayList or rewrite it with IntStream.range first. Only then does parallel() have a fair chance.
Trap: blocking calls inside parallel streams
A blocking call is one where the thread just waits: a network request to a payment server, a database query, reading a file or Thread.sleep. While a thread waits, its core is idle.
Example 3 · Trap: network calls inside a parallel stream
import java.util.List;import java.util.concurrent.ForkJoinPool;import java.util.stream.IntStream;
public class BlockingCallDemo { // stands in for a 100 ms call to a payment server static String checkStatus(int orderId) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "PAID-" + orderId; }
public static void main(String[] args) { List<Integer> orders = IntStream.rangeClosed(1, 48).boxed().toList(); System.out.println("Common pool threads: " + ForkJoinPool.commonPool().getParallelism());
long start = System.nanoTime(); List<String> seq = orders.stream().map(BlockingCallDemo::checkStatus).toList(); System.out.println("Sequential: " + (System.nanoTime() - start) / 1_000_000 + " ms for " + seq.size() + " calls");
start = System.nanoTime(); List<String> par = orders.parallelStream().map(BlockingCallDemo::checkStatus).toList(); System.out.println("Parallel: " + (System.nanoTime() - start) / 1_000_000 + " ms for " + par.size() + " calls"); }}Common pool threads: 11 Sequential: 5193 ms for 48 calls Parallel: 422 ms for 48 calls
What this code does
- The parallel time is not 100 ms: only the pool threads plus
maincan wait at once, so 48 calls take several rounds. On a 4-core server with 3 pool threads, they would take about 12 rounds, 1.2 seconds. - During that time every pool thread is asleep, so any other parallel stream in the application must wait as well. Waiting work belongs in its own thread pool, not in the common pool.
The common pool has only as many threads as there are cores minus one, because it was built for calculations, not for waiting. Fifty network calls of 200 ms each on a 4-core server run about four at a time, so the job takes many rounds, not 200 ms. Worse, while those threads wait, every other parallel stream in the application has no threads left and waits too. So never put network, database or file calls inside a parallel stream. Waiting work needs its own pool of threads or asynchronous tools, which the Multithreading and Concurrency section covers.
Measuring simply, and why one run can mislead
System.nanoTime() returns a time in nanoseconds that is only useful as a difference: take it before the work, take it after, and subtract. Divide by 1,000,000 for milliseconds.
Example 4 · Timing a small task and a heavy task
import java.util.function.LongSupplier;import java.util.stream.LongStream;
public class TimingDemo { static boolean isPrime(long n) { if (n < 2) { return false; } for (long d = 2; d * d <= n; d++) { if (n % d == 0) { return false; } } return true; }
static void measure(String label, LongSupplier task) { for (int run = 1; run <= 3; run++) { long start = System.nanoTime(); long result = task.getAsLong(); double ms = (System.nanoTime() - start) / 1_000_000.0; System.out.printf("%s run %d: %8.2f ms (result %d)%n", label, run, ms, result); } }
public static void main(String[] args) { measure("small sequential", () -> LongStream.rangeClosed(1, 1_000).sum()); measure("small parallel ", () -> LongStream.rangeClosed(1, 1_000).parallel().sum()); measure("heavy sequential", () -> LongStream.rangeClosed(1, 2_000_000).filter(TimingDemo::isPrime).count()); measure("heavy parallel ", () -> LongStream.rangeClosed(1, 2_000_000).parallel().filter(TimingDemo::isPrime).count()); }}small sequential run 1: 9.62 ms (result 500500) small sequential run 2: 0.14 ms (result 500500) small sequential run 3: 0.13 ms (result 500500) small parallel run 1: 12.55 ms (result 500500) small parallel run 2: 1.87 ms (result 500500) small parallel run 3: 0.45 ms (result 500500) heavy sequential run 1: 872.27 ms (result 148933) heavy sequential run 2: 855.29 ms (result 148933) heavy sequential run 3: 905.54 ms (result 148933) heavy parallel run 1: 142.58 ms (result 148933) heavy parallel run 2: 144.84 ms (result 148933) heavy parallel run 3: 133.62 ms (result 148933)
What this code does
- For 1000 numbers the parallel version is slower: starting threads and merging cost more than adding a few numbers. The first run of each task is slower than the next ones, because the JIT compiler is still warming up.
- Counting primes up to 2 million is big N and real work per number, so the parallel version is several times faster after warm-up. The result is printed on every line, so the JVM cannot skip the work, and both versions agree.
One run proves very little. The JVM starts by interpreting your code and compiles the busy parts to fast machine code while the program runs; this is the JIT (just-in-time) compiler, and it makes the first runs slower. Garbage collection pauses, other programs and the CPU changing speed add noise. A fair quick test runs the work a few times to warm up, measures several runs, compares the best or middle time, and uses the result so the JVM cannot skip the work. For real decisions, Java developers use JMH (Java Microbenchmark Harness), a tool that handles warm-up and noise for you. The numbers in this lesson are samples from one laptop; yours will differ.
Interview point: should every stream be parallel?
No. A good answer gives the reasons: most collections are too small for the split and merge costs to pay off; parallel needs stateless lambdas and associative operations, and any shared state becomes a bug; order-sensitive steps lose most of the gain; every parallel stream shares one pool, so one misuse slows the whole application; and in a web server, many requests already keep all cores busy, so parallel streams inside each request only add overhead.
The usual answer is: start sequential, and switch to parallel only for large, CPU-heavy work on a splittable source, after a measurement shows a real gain and a test shows the same result.
Next step
Check your understanding
12 quick questions