Java Parallel Streams: Parallel Decomposition, Reductions and Ordering (OCP 21)
Parallel streams for the OCP 21 exam: parallel() and parallelStream(), the common fork/join pool, forEach versus forEachOrdered, findAny and findFirst, reduce rules for identity and associativity, concurrent collectors, stateful lambdas and ThreadLocalRandom.
kvi5hnuCode Sprout team member9 min readOn this page
Every stream in Chapter 10 was serial: it processed one element at a time, in order. A parallel stream splits its elements into chunks and processes them on several threads at once. Switching a stream to parallel can be one method call, but it can also change the order of results and, with careless lambdas, the results themselves. This article covers what changes and how to write pipelines that give the same answer either way.
Creating a parallel stream
There are two ways:
List<Integer> tracks = List.of(1, 2, 3, 4);
Stream<Integer> p1 = tracks.stream().parallel(); // from any existing stream
Stream<Integer> p2 = tracks.parallelStream(); // straight from a Collection
parallelStream()exists only onCollection, not onStream.parallel()exists onStreamand the primitive streams (IntStreamand others), but not onList.isParallel()reports whether a stream is parallel.- A whole pipeline runs either serially or in parallel. If you call both
parallel()andsequential(), the last call wins for the entire pipeline, not just the operations after it.
Parallel streams run on the common ForkJoinPool, ForkJoinPool.commonPool(). By default it has about one thread fewer than the number of CPUs, and the calling thread helps too. They don't use virtual threads.
Parallel decomposition
A parallel decomposition splits a task into smaller pieces that can be done concurrently, then puts the results back together. Imagine a slow method that takes 200 ms per element:
tracks.stream().map(Solution::slowSquare).forEach(System.out::println);
// serial: about 4 x 200 ms = 800 ms, prints 1 4 9 16
tracks.parallelStream().map(Solution::slowSquare).forEach(System.out::println);
// parallel: about 200 ms with 4+ CPUs, prints e.g. 9 1 16 4
The time depends on how many CPUs are available. With fewer cores you might see 400 ms or 600 ms. The exam asks what's possible, not exact timings.
Ordering
forEach on a parallel stream processes elements in whatever order the threads finish. To act on the elements in their original encounter order, use forEachOrdered:
tracks.parallelStream().map(Solution::slowSquare).forEachOrdered(System.out::println);
// always 1 4 9 16, and map() still runs in parallel

| Operation on a parallel stream | Result |
|---|---|
forEach | any order |
forEachOrdered | encounter order (slower) |
findAny() | any element. Results vary from run to run. |
findFirst(), limit(n), skip(n) | same result as serial, but the threads must coordinate, which can be slower |
collect(Collectors.toList()), toList() | list in encounter order |
sorted().forEach(...) | still any order. sorted() doesn't make the terminal forEach ordered. |
findAny() isn't guaranteed to return the first element even on a serial stream, although in practice it usually does. On a parallel stream the result really does vary.
Parallel reductions with reduce()
reduce() combines elements into one value. Recall the three-argument form:
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)
In parallel, each chunk starts from the identity, the accumulator folds the chunk's elements in, and the combiner joins the partial results:
String word = List.of('t', 'u', 'n', 'e').parallelStream()
.reduce("", (s, c) -> s + c, String::concat); // "tune"
Partial results are combined in encounter order, so "tune" never comes out as "nute". That's guaranteed as long as you follow the rules:
- The identity must really be an identity, meaning
combiner(identity, x)equalsx. Using"X"as the identity for concatenation gives"Xtune"-style results serially, but"XtXuXnXe"in parallel, because every chunk starts with its own"X". - The accumulator and combiner must be associative: grouping mustn't matter. Addition and concatenation are associative, but subtraction isn't.
reduce(0, (a, b) -> a - b)on 1 to 6 gives -21 serially and other values in parallel. - They must be stateless and non-interfering. They shouldn't change shared state or the stream's source.
These rules apply to serial streams too. Serial streams just hide the problems. The two-argument form reduce(identity, accumulator) works when the result has the same type as the elements. When the types differ (characters in, String out), you need the three-argument form. The combiner also lets Java split the work efficiently.
Parallel reductions with collect()
collect() also has a three-argument form, which takes a supplier of the result container, an accumulator and a combiner:
SortedSet<String> set = Stream.of("oboe", "harp", "bass", "drum").parallel()
.collect(ConcurrentSkipListSet::new, Set::add, Set::addAll);
System.out.println(set); // [bass, drum, harp, oboe]
Each thread fills its own container, and the combiner merges them.
Concurrent collectors
Ordinary collectors work on parallel streams too: each thread builds a partial result, and Java merges them. A truly concurrent reduction, where all threads add into one shared container, happens only when all three of these hold:
- the stream is parallel;
- the collector has the characteristic
Collector.Characteristics.CONCURRENT; - the stream is unordered, or the collector has
Characteristics.UNORDERED.
| Collector | Characteristics | Concurrent reduction? |
|---|---|---|
Collectors.toSet() | UNORDERED, IDENTITY_FINISH | no, because it isn't CONCURRENT |
Collectors.toConcurrentMap(...) | CONCURRENT, UNORDERED, ... | yes |
Collectors.groupingByConcurrent(...) | CONCURRENT, UNORDERED, ... | yes |
ConcurrentMap<Integer, String> byLength = Stream.of("cello", "viola", "lute", "harp").parallel()
.collect(Collectors.toConcurrentMap(String::length, s -> s, (a, b) -> a + "," + b));
// {4=lute,harp, 5=cello,viola}: the merged order isn't guaranteed
ConcurrentMap<Integer, List<String>> groups = Stream.of("cello", "viola", "lute", "harp").parallel()
.collect(Collectors.groupingByConcurrent(String::length));
Both return a ConcurrentMap. In practice it's a ConcurrentHashMap, but only the interface is promised. As with toMap, toConcurrentMap without a merge function throws IllegalStateException on a duplicate key.
Avoid stateful lambdas
A lambda is stateful if its result depends on state that can change while the pipeline runs, such as a list outside the stream:
List<Integer> evens = Collections.synchronizedList(new ArrayList<>());
IntStream.rangeClosed(1, 10).parallel()
.filter(n -> n % 2 == 0)
.forEach(evens::add); // STATEFUL: order varies, e.g. [6, 8, 10, 2, 4]
The stateless version lets the stream build the result:
List<Integer> evens = IntStream.rangeClosed(1, 10).parallel()
.filter(n -> n % 2 == 0).boxed().toList(); // always [2, 4, 6, 8, 10]
With a plain ArrayList instead of a synchronized one, the stateful version could also lose elements or throw exceptions. Avoid side effects in serial streams too, so the code stays correct if someone makes it parallel later.
Random numbers in multithreaded code
Math.random() and a shared Random are thread-safe, but threads compete for them. In concurrent code, use ThreadLocalRandom.current(). Each thread gets its own generator, and you must not share the returned object between threads:
| Method | Returns |
|---|---|
nextInt(bound) | one int from 0 (inclusive) to bound (exclusive) |
nextInt(origin, bound) | one int from origin (inclusive) to bound (exclusive) |
ints() | an unlimited IntStream of any int values |
ints(origin, bound) | an unlimited stream within the range |
ints(count) | count values |
ints(count, origin, bound) | count values within the range |
doubles(), longs(), nextDouble() and nextLong() follow the same pattern.
When parallel helps
Parallel streams pay off for large data sets where each element needs real, independent work and the source splits easily (ArrayList, arrays, IntStream.range). They can be slower for small data, for sources that split poorly (LinkedList, Stream.iterate), for order-dependent operations, and for work that mostly waits on I/O. For waiting work, virtual threads (article 78) are the better tool.
What's current
Stream.toList()(Java 16) returns an unmodifiable list in encounter order, also for parallel streams.- Stream gatherers (
Stream.gather, final in Java 24) add custom intermediate operations.Gatherers.mapConcurrent(Java 24) runs a mapping function on virtual threads with a concurrency limit, which is a better fit than parallel streams for I/O-bound work. Neither is on the Java 21 exam. RandomGenerator(Java 17) is the common interface implemented byRandom,ThreadLocalRandomand newer algorithms.
Exam traps from this article
A complete example
A music app squares track numbers slowly and handles words and instruments. The program checks how parallel streams are created, times serial and parallel versions of four 200 ms tasks, and shows which operations keep encounter order. It compares findFirst with findAny, shows correct and broken reduce calls, uses concurrent collectors and their characteristics, contrasts stateful and stateless code, and uses ThreadLocalRandom from many threads.
Results that legitimately vary, such as timing, findAny and the parallel subtraction, are printed as true/false checks so the output is the same on every run.
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Solution {
static int slowSquare(int n) { // pretend this calls a slow service
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return n * n;
}
static long millis(Runnable job) {
long start = System.nanoTime();
job.run();
return (System.nanoTime() - start) / 1_000_000;
}
static String names(Collector<?, ?, ?> c) {
return c.characteristics().stream().map(Enum::name).sorted().collect(Collectors.joining(", ", "[", "]"));
}
public static void main(String[] args) {
List<Integer> tracks = List.of(1, 2, 3, 4);
System.out.println("== 1. Making a stream parallel");
System.out.println(" stream().isParallel(): " + tracks.stream().isParallel());
System.out.println(" parallelStream().isParallel(): " + tracks.parallelStream().isParallel());
System.out.println(" stream().parallel().isParallel(): " + tracks.stream().parallel().isParallel());
System.out.println(" parallel().sequential() -> last call wins: "
+ tracks.stream().parallel().map(x -> x).sequential().isParallel());
System.out.println("\n== 2. Parallel decomposition: 4 tasks of 200 ms");
long serial = millis(() -> tracks.stream().map(Solution::slowSquare).forEach(x -> { }));
long parallel = millis(() -> tracks.parallelStream().map(Solution::slowSquare).forEach(x -> { }));
System.out.println(" serial took about 800 ms: " + (serial >= 780));
System.out.println(" parallel took under 600 ms: " + (parallel < 600)
+ " (using " + ForkJoinPool.commonPool().getClass().getSimpleName() + ".commonPool() plus the caller)");
System.out.println("\n== 3. Order");
List<Integer> seen = Collections.synchronizedList(new ArrayList<>());
IntStream.rangeClosed(1, 50).parallel().forEach(seen::add);
List<Integer> sortedCopy = new ArrayList<>(seen);
Collections.sort(sortedCopy);
System.out.println(" forEach saw all 50 values: " + sortedCopy.equals(IntStream.rangeClosed(1, 50).boxed().toList()));
StringBuilder ordered = new StringBuilder();
tracks.parallelStream().map(Solution::slowSquare).forEachOrdered(n -> ordered.append(n).append(' '));
System.out.println(" forEachOrdered: " + ordered.toString().trim());
System.out.println(" toList() keeps encounter order: "
+ IntStream.rangeClosed(1, 10).parallel().map(n -> n * 10).boxed().toList());
System.out.println(" sorted() then collect(joining): " + Stream.of("drum", "bass", "harp", "oboe").parallel()
.sorted().collect(Collectors.joining(" ")));
System.out.println("\n== 4. findFirst, findAny, skip and limit");
System.out.println(" findFirst(): " + IntStream.rangeClosed(1, 100).parallel().findFirst().getAsInt());
int any = IntStream.rangeClosed(1, 100).parallel().findAny().getAsInt();
System.out.println(" findAny() is some element: " + (any >= 1 && any <= 100));
System.out.println(" skip(5).limit(2) -> same as serial: "
+ IntStream.rangeClosed(1, 100).parallel().skip(5).limit(2).boxed().toList());
System.out.println("\n== 5. reduce() on a parallel stream");
List<Character> letters = List.of('t', 'u', 'n', 'e');
System.out.println(" 3-arg reduce (identity \"\"): "
+ letters.parallelStream().reduce("", (s, c) -> s + c, String::concat));
System.out.println(" sum with identity 0: " + IntStream.rangeClosed(1, 6).parallel().reduce(0, Integer::sum));
System.out.println(" subtraction, serial: " + IntStream.rangeClosed(1, 6).reduce(0, (a, b) -> a - b));
Set<Integer> differences = new TreeSet<>();
for (int i = 0; i < 20; i++)
differences.add(IntStream.rangeClosed(1, 6).parallel().reduce(0, (a, b) -> a - b));
System.out.println(" subtraction, parallel, differs from serial: " + !differences.equals(Set.of(-21)));
System.out.println(" identity \"X\" serial: " + Stream.of("a", "b", "c", "d").reduce("X", String::concat));
System.out.println(" identity \"X\" parallel: " + Stream.of("a", "b", "c", "d").parallel().reduce("X", String::concat));
System.out.println("\n== 6. collect() and concurrent collectors");
SortedSet<String> set = Stream.of("oboe", "harp", "bass", "drum").parallel()
.collect(ConcurrentSkipListSet::new, Set::add, Set::addAll);
System.out.println(" 3-arg collect into ConcurrentSkipListSet: " + set);
ConcurrentMap<Integer, String> byLength = Stream.of("cello", "viola", "lute", "harp").parallel()
.collect(Collectors.toConcurrentMap(String::length, s -> s, (a, b) -> a.compareTo(b) < 0 ? a + "," + b : b + "," + a));
System.out.println(" toConcurrentMap: " + new TreeMap<>(byLength) + " (a " + byLength.getClass().getSimpleName() + ")");
ConcurrentMap<Integer, List<String>> groups = Stream.of("cello", "viola", "lute", "harp").parallel()
.collect(Collectors.groupingByConcurrent(String::length));
groups.values().forEach(Collections::sort);
System.out.println(" groupingByConcurrent: " + new TreeMap<>(groups));
System.out.println(" toSet() characteristics: " + names(Collectors.toSet()));
System.out.println(" groupingByConcurrent() characteristics: " + names(Collectors.groupingByConcurrent(String::length)));
System.out.println("\n== 7. Stateful lambdas: don't");
List<Integer> sideEffect = Collections.synchronizedList(new ArrayList<>());
IntStream.rangeClosed(1, 1_000).parallel().filter(n -> n % 2 == 0).forEach(sideEffect::add);
List<Integer> stateless = IntStream.rangeClosed(1, 1_000).parallel().filter(n -> n % 2 == 0).boxed().toList();
System.out.println(" both have 500 even numbers: " + (sideEffect.size() == 500 && stateless.size() == 500));
System.out.println(" stateless toList() is in order: " + stateless.equals(stateless.stream().sorted().toList()));
System.out.println("\n== 8. ThreadLocalRandom for multithreaded code");
ThreadLocalRandom random = ThreadLocalRandom.current();
System.out.println(" ints(5, 1, 7) all in 1..6: " + random.ints(5, 1, 7).allMatch(n -> n >= 1 && n <= 6));
int roll = random.nextInt(1, 7);
System.out.println(" nextInt(1, 7) in 1..6: " + (roll >= 1 && roll <= 6));
long evens = IntStream.range(0, 10_000).parallel()
.map(i -> ThreadLocalRandom.current().nextInt(100)).filter(n -> n % 2 == 0).count();
System.out.println(" 10,000 parallel draws, roughly half even: " + (evens > 4_000 && evens < 6_000));
}
}
Output:
== 1. Making a stream parallel
stream().isParallel(): false
parallelStream().isParallel(): true
stream().parallel().isParallel(): true
parallel().sequential() -> last call wins: false
== 2. Parallel decomposition: 4 tasks of 200 ms
serial took about 800 ms: true
parallel took under 600 ms: true (using ForkJoinPool.commonPool() plus the caller)
== 3. Order
forEach saw all 50 values: true
forEachOrdered: 1 4 9 16
toList() keeps encounter order: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
sorted() then collect(joining): bass drum harp oboe
== 4. findFirst, findAny, skip and limit
findFirst(): 1
findAny() is some element: true
skip(5).limit(2) -> same as serial: [6, 7]
== 5. reduce() on a parallel stream
3-arg reduce (identity ""): tune
sum with identity 0: 21
subtraction, serial: -21
subtraction, parallel, differs from serial: true
identity "X" serial: Xabcd
identity "X" parallel: XaXbXcXd
== 6. collect() and concurrent collectors
3-arg collect into ConcurrentSkipListSet: [bass, drum, harp, oboe]
toConcurrentMap: {4=harp,lute, 5=cello,viola} (a ConcurrentHashMap)
groupingByConcurrent: {4=[harp, lute], 5=[cello, viola]}
toSet() characteristics: [IDENTITY_FINISH, UNORDERED]
groupingByConcurrent() characteristics: [CONCURRENT, IDENTITY_FINISH, UNORDERED]
== 7. Stateful lambdas: don't
both have 500 even numbers: true
stateless toList() is in order: true
== 8. ThreadLocalRandom for multithreaded code
ints(5, 1, 7) all in 1..6: true
nextInt(1, 7) in 1..6: true
10,000 parallel draws, roughly half even: true
Points to notice:
- The last of
parallel()andsequential()decided the whole pipeline:false. - The parallel run of four 200 ms tasks finished in well under the serial 800 ms.
forEachOrderedandtoList()kept encounter order, even though the mapping ran on several threads.findFirst()returned 1 andskip(5).limit(2)gave[6, 7], just as a serial stream would.- The identity
"X"was applied once per chunk in parallel, givingXaXbXcXd, while the serial version gaveXabcd. toSet()reported onlyUNORDEREDandIDENTITY_FINISH, butgroupingByConcurrentaddedCONCURRENT.
Common questions
Should I make all my streams parallel? No. Measure first. Splitting, thread hand-off and merging cost time, so small or I/O-bound pipelines often run slower in parallel.
Can I choose the thread pool for a parallel stream?
Not directly. They use the common pool. Its size can be changed with the system property java.util.concurrent.ForkJoinPool.common.parallelism, and running the stream inside a task submitted to your own ForkJoinPool also works, though that relies on an implementation detail.
Is collect(Collectors.toList()) safe on a parallel stream?
Yes. Each thread builds its own list, and Java merges them in encounter order. The unsafe part is adding to an outside list from forEach.
Summary
- Create parallel streams with
collection.parallelStream()orstream.parallel(). They run on the common fork/join pool. - Parallel
forEachandfindAnyhave no fixed order.forEachOrdered,findFirst,limit,skipandtoList()respect encounter order. reduceandcollectwork in parallel if the identity is a true identity and the operations are associative and stateless. Use the three-argument versions.toConcurrentMapandgroupingByConcurrentareCONCURRENTandUNORDEREDcollectors that give real parallel reductions into aConcurrentMap.- Avoid stateful lambdas, and use
ThreadLocalRandom.current()for random numbers in multithreaded code.
Practice quiz
Test yourself with the parallel streams quiz: 10 exam-style questions with explanations.
You've finished Chapter 13. Check your understanding of the whole chapter with the Chapter 13 review quiz: 20 mixed questions on threads, executors, thread safety, locks, concurrent collections and parallel streams.
Previous: Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
Next: Java File and Path: Creating Paths and Converting Between Them (OCP 21)
Related reading
- Java Collectors: joining, toMap, groupingBy, partitioningBy and teeing (OCP 21)
- Java Primitive Streams: IntStream, LongStream, DoubleStream and Summary Statistics (OCP 21)
- Java Stream Intermediate Operations: filter, map, flatMap, sorted, distinct, limit and peek (OCP 21)
- Java Stream Terminal Operations: count, min, max, find, match, forEach, reduce and collect (OCP 21)
- Java Streams: Pipeline Flow and Creating Finite and Infinite Streams (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.