Stream vs Parallel Stream in Java
A sequential stream processes its elements one after another on the calling thread. A parallel stream splits its source into parts, processes the parts on several threads of the common ForkJoinPool, and combines the partial results. Both are the same java.util.stream.Stream type, introduced in Java 8; the execution mode is a property of the pipeline.
You get a sequential stream from collection.stream() and a parallel one from collection.parallelStream() or by calling parallel() on any stream. This tutorial shows how the two modes differ in threads, ordering, correctness and speed.
1. Syntax and Method Signatures
// java.util.Collection (Java 8)
default Stream<E> stream()
default Stream<E> parallelStream()
// java.util.stream.BaseStream (Java 8)
S parallel() // returns an equivalent parallel stream
S sequential() // returns an equivalent sequential stream
boolean isParallel() // true if a terminal operation would run in parallel
S is the stream type itself, such as Stream<T> or IntStream. Both parallel() and sequential() are intermediate operations that set a flag for the whole pipeline; the last call wins.
2. How Sequential and Parallel Streams Run
When the terminal operation of a parallel pipeline runs, the source's Spliterator splits the data into smaller chunks. Each chunk becomes a task in the common ForkJoinPool, and the calling thread helps with the work. When the tasks finish, their partial results are combined, for example by adding partial sums or merging partial lists.
Splitting and combining are the reasons parallel streams are not automatically faster. Arrays, ArrayList and IntStream.range() split cheaply; LinkedList and Stream.iterate() split poorly. The common pool has, by default, one thread fewer than the number of available processors, and it is shared by every parallel stream in the JVM.
3. Java Examples
Example 1: The same result in both modes
Count the numbers between 1 and 2,000,000 whose digit sum is divisible by 7, sequentially and in parallel.
import java.util.stream.IntStream;
public class SameResultBothModes {
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
long sequential = IntStream.rangeClosed(1, 2_000_000)
.filter(n -> digitSum(n) % 7 == 0)
.count();
long parallel = IntStream.rangeClosed(1, 2_000_000)
.parallel()
.filter(n -> digitSum(n) % 7 == 0)
.count();
System.out.println("Sequential count: " + sequential);
System.out.println("Parallel count: " + parallel);
}
}
Sequential count: 285773 Parallel count: 285773
How it works: The filter depends only on each number, and counting is associative, so both modes must agree. The parallel version splits the range across worker threads and adds up their counts.
Example 2: Ordering with forEach() and forEachOrdered() (Java 9+)
Print five invoice numbers from a parallel stream, first with forEach(), then with forEachOrdered().
import java.util.List;
public class ParallelOrdering {
public static void main(String[] args) {
List<String> invoices = List.of("INV-1", "INV-2", "INV-3", "INV-4", "INV-5");
System.out.print("forEach: ");
invoices.parallelStream().forEach(id -> System.out.print(id + " "));
System.out.println();
System.out.print("forEachOrdered: ");
invoices.parallelStream().forEachOrdered(id -> System.out.print(id + " "));
System.out.println();
}
}
forEach: INV-5 INV-2 INV-1 INV-4 INV-3 forEachOrdered: INV-1 INV-2 INV-3 INV-4 INV-5
The first line changes from run to run; the line above is one real run. The second line is always in order.
How it works: forEach() on a parallel stream runs the action on whichever thread finishes first, so the order is not guaranteed. forEachOrdered() respects the list's encounter order, at the cost of some parallelism.
Example 3: The last parallel() or sequential() call wins
Check which mode a pipeline runs in after switching back and forth.
import java.util.stream.Stream;
public class LastCallWins {
public static void main(String[] args) {
Stream<String> a = Stream.of("x", "y", "z");
System.out.println("plain: " + a.isParallel());
Stream<String> b = Stream.of("x", "y", "z").parallel();
System.out.println("parallel(): " + b.isParallel());
Stream<String> c = Stream.of("x", "y", "z").parallel().map(String::toUpperCase).sequential();
System.out.println("parallel()...sequential(): " + c.isParallel());
}
}
plain: false parallel(): true parallel()...sequential(): false
How it works: The mode is one flag for the entire pipeline, not per step. You cannot make only the map() parallel: the final call before the terminal operation decides how every step runs.
Example 4: Shared mutable state breaks in parallel
Collect the even numbers from 1 to 10,000. Adding to a plain ArrayList from a parallel lambda is unsafe; collecting is safe.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SafeParallelCollect {
public static void main(String[] args) {
List<Integer> evens = IntStream.rangeClosed(1, 10_000)
.parallel()
.filter(n -> n % 2 == 0)
.boxed()
.collect(Collectors.toList());
System.out.println("Size: " + evens.size());
System.out.println("First: " + evens.get(0) + ", last: " + evens.get(evens.size() - 1));
}
}
Size: 5000 First: 2, last: 10000
How it works: Each worker thread collects into its own temporary list, and the lists are merged in encounter order, so the result is complete and ordered. Writing list.add(n) inside forEach() on a parallel stream instead can lose elements or throw ArrayIndexOutOfBoundsException, because ArrayList is not thread-safe.
4. Sequential vs Parallel Stream Comparison
| Aspect | Sequential stream | Parallel stream |
|---|---|---|
| Created with | stream(), Stream.of() | parallelStream() or .parallel() |
| Threads | The calling thread | Common ForkJoinPool workers plus the caller |
forEach() order | Encounter order (in practice) | Unpredictable; use forEachOrdered() |
findAny() | Usually the first element | Any element |
| Shared mutable state | Risky but often works | Gives wrong results or exceptions |
| Overhead | None | Splitting, task scheduling and combining |
| Best for | Small or medium data, I/O, ordered work | Large data, CPU-heavy, independent operations |
Both modes must produce the same result for a correct pipeline. If they do not, the pipeline has a side effect or an operation that is not associative. See Parallel Stream Introduction and Sequential vs Parallel Performance.
5. Real-World Use Cases
- Sequential for everyday code: filtering a page of orders, mapping DTOs or building a response is small work where sequential streams are simplest and fastest.
- Parallel for large CPU-bound batches: scoring millions of transactions for fraud rules or computing statistics over a big in-memory array.
- Sequential for I/O: calling a database or REST service per element blocks threads in the shared pool; use an executor or virtual threads instead.
6. Important Points
- Associativity matters.
reduce()in parallel needs an associative function; subtraction, for example, gives different answers. - Encounter order is kept by
toList(),collect(),findFirst()andforEachOrdered(), even in parallel. - The common pool is shared. A slow, blocking lambda in one parallel stream slows down every other parallel stream in the application.
- Exceptions thrown in a worker thread are rethrown from the terminal operation on the calling thread.
- Small inputs are usually slower in parallel; the break-even point depends on the work per element, so measure.
7. Common Mistakes and Best Practices
Updating a shared counter
int[] total = {0};
orders.parallelStream().forEach(o -> total[0] += o.amount()); // lost updates
Let the stream combine the values instead:
import java.util.stream.IntStream;
public class ParallelSumFix {
public static void main(String[] args) {
int total = IntStream.rangeClosed(1, 100_000)
.parallel()
.map(n -> n % 50)
.sum();
System.out.println("Total: " + total);
}
}
Total: 2450000
Other mistakes to avoid
- Making everything parallel. Start sequential and switch only after a benchmark shows a gain.
- Using
parallel()withLinkedListorStream.iterate(). These sources split badly. - Relying on
findAny()returning the first element. UsefindFirst()when position matters. - Blocking calls inside a parallel stream. Network or database calls tie up shared pool threads.
8. Summary
- Sequential streams run on the calling thread; parallel streams split the source across the common
ForkJoinPool. parallel()andsequential()set the mode of the whole pipeline, and the last call wins.- A correct pipeline gives the same result in both modes; shared mutable state and non-associative functions break that.
- Use
forEachOrdered()or ordered collectors when order matters in parallel. - Prefer sequential streams by default and measure before going parallel.
9. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between stream() and parallelStream()?
stream() returns a sequential stream that runs on the calling thread. parallelStream() returns a parallel stream whose terminal operation splits the work across threads of the common ForkJoinPool and combines the partial results.
Q2. Is a parallel stream always faster?
No. Splitting the data, scheduling tasks and combining results has a cost. Parallel streams help only for large data sets with CPU-heavy, independent work on a source that splits well, such as an array or ArrayList.
Q3. Which thread pool do parallel streams use?
They use the common ForkJoinPool, which by default has one fewer thread than the number of available processors. The calling thread also helps. The pool is shared by all parallel streams in the JVM.
Q4. Can I make only part of a pipeline parallel?
No. parallel() and sequential() set the mode of the whole pipeline, and the last call before the terminal operation wins.
Q5. Does a parallel stream keep the order of elements?
Terminal operations such as toList(), collect(), findFirst() and forEachOrdered() respect encounter order even in parallel. forEach() and findAny() do not, so their results can differ from run to run.