Parallel stream constraints
What you will learn
Parallel streams may split a computation across workers. They are useful only when the operation remains correct under splitting and the workload benefits from it. Design the reduction for correctness first, then measure performance rather than assuming parallel execution is faster.
- Explain identity, associativity and statelessness in a parallel pipeline.
- Use a collector instead of mutating a shared external container.
- Distinguish result order from execution order and test invariants.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Compare sequential and parallel totals
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var nums = IntStream.rangeClosed(1, 1000).boxed().toList(); long a = nums.stream().mapToLong(Integer::longValue).sum(); long b = nums.parallelStream().mapToLong(Integer::longValue).sum(); System.out.println(a); System.out.println(a == b); }}Expected output:
500500trueAddition over this bounded input yields the same value independent of partitioning.
Parallel does not mean ordered callbacks
parallelStream() requests a parallel pipeline; parallel() and sequential() select a mode for the pipeline. The implementation chooses how to split work. Encounter order is not execution order. forEach may process elements in a different order; forEachOrdered respects encounter order when present. findAny can select an arbitrary matching element, while findFirst respects an existing encounter order. Test allowed outcomes rather than a guessed schedule. Avoid blocking network work or long-running tasks in a shared parallel stream environment.
Reduction must survive splitting
For addition, an identity of zero works for every partition. An identity of ten can be applied multiple times when split and gives a different result. Subtraction is not associative. Keep callbacks stateless and noninterfering; do not modify an ordinary source during execution. Avoid writes into an externally shared ArrayList even if it appeared to work sequentially. A nonconcurrent collector may safely use separate mutable accumulation containers for partial results; its combiner merges them. A concurrent collector has a separate contract and may allow shared accumulation when ordering permits.
Decide based on workload
Parallel streams incur splitting, coordination and merging costs. Small lists, order-sensitive operations and blocking I/O often do not benefit. Measure equivalent sequential and parallel operations in a controlled benchmark; this lesson does not report performance measurements. Floating-point operations can differ by rounding. Keep tests finite, deterministic, and assert the resulting values rather than worker count or timing. Gatherers, a newer stream extension API finalized in Java 24, are outside this Java 21-tested batch; a separate version-scoped lesson is needed.
Collect without an external shared list
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var names = List.of("ada", "bo", "cy"); var labels = names.parallelStream().map(s -> "ID-" + s).collect(Collectors.toCollection(ArrayList::new)); System.out.println(labels); }}Expected output:
[ID-ada, ID-bo, ID-cy]The collector manages accumulation and the ordered result rather than callbacks mutating a shared list.
Check an arbitrary match without guessing
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var values = List.of(5, 8, 12, 3); int picked = values.parallelStream().filter(n -> n % 2 == 0).findAny().orElseThrow(); System.out.println(picked == 8 || picked == 12); System.out.println(values.parallelStream().filter(n -> n % 2 == 0).findFirst().orElseThrow()); }}Expected output:
true8The first assertion accepts either matching value. findFirst returns the first matching value in this ordered source.
Custom mutable reduction with isolated containers
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var result = Stream.of("a", "b", "c").parallel().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append); System.out.println(result.toString()); IntStream.rangeClosed(1, 3).parallel().forEachOrdered(System.out::println); }}Expected output:
abc123Each partial builder can be merged in encounter order. forEachOrdered prints in the ordered sequence.
Common mistakes
Do not use a fixed sleep to prove worker order, or claim a speedup from one run. Never use a nonneutral identity or shared mutable accumulator to make parallel code appear simpler. Prefer a sequential pipeline unless parallelism has a measured benefit.
Practice
For the range 1 through 100 inclusive, select multiples of 5, square them as long values, and sum them using sequential and parallel pipelines. Print both sums and their equality. Do not mutate any external accumulator.
Expected output:
7175071750trueCompare your answer with the manual practice criteria.
Official reading: Java SE 25 Stream API · Stream package contracts · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parallel stream constraints — knowledge check
Original Java stream contract and boundary questions. Java 21-compatible scope.
Why is 10 a bad identity for addition in parallel reduce?
Which terminal operation respects encounter order for actions?
What is a safe way to accumulate a list in parallel?
What should a test of findAny assert?
When should parallel execution be preferred?