Parallel Streams in Java: An Introduction
A parallel stream is a stream whose pipeline is executed by several threads at once. It is part of the java.util.stream API since Java 8: any stream becomes parallel with parallel(), and any collection offers parallelStream(). Behind the scenes, the work is split into chunks and processed by the common ForkJoinPool.
This tutorial introduces how parallel streams split, process and combine data, how to see which threads are used, and which operations behave differently in parallel. Later pages cover performance, thread safety and best practices.
1. Creating Parallel Streams
// Creating parallel streams
Stream<E> Collection<E>.parallelStream() // Java 8: possibly parallel
S BaseStream.parallel() // Java 8: switch any stream to parallel
boolean BaseStream.isParallel()
// The pool behind them (java.util.concurrent.ForkJoinPool, Java 8)
static ForkJoinPool commonPool()
int getParallelism() // default: available processors - 1 (at least 1)
The common pool's size can be changed for the whole JVM with the system property java.util.concurrent.ForkJoinPool.common.parallelism.
2. How Parallel Streams Work
When the terminal operation of a parallel pipeline starts, the source's Spliterator is split repeatedly with trySplit() until the chunks are small enough. Each chunk becomes a task submitted to the common ForkJoinPool. Idle workers steal tasks from busy ones, which balances the load. The calling thread also takes part.
When tasks finish, their partial results are combined: partial sums are added, partial lists are concatenated, partial maps are merged. Operations that depend on encounter order, such as findFirst(), limit() and forEachOrdered(), still return the same answer as a sequential stream, but must coordinate to do so.
3. Java Examples
Example 1: Turning a pipeline parallel
Count the numbers up to five million whose square ends in the digit 6, sequentially and in parallel.
import java.util.stream.LongStream;
public class FirstParallelStream {
public static void main(String[] args) {
long sequential = LongStream.rangeClosed(1, 5_000_000)
.filter(n -> (n * n) % 10 == 6)
.count();
long parallel = LongStream.rangeClosed(1, 5_000_000)
.parallel()
.filter(n -> (n * n) % 10 == 6)
.count();
System.out.println("Sequential: " + sequential);
System.out.println("Parallel: " + parallel);
}
}
Sequential: 1000000 Parallel: 1000000
How it works: Only parallel() was added. A square ends in 6 when the number ends in 4 or 6, which is one in five numbers. The filter is independent per element and counting is associative, so both modes must agree.
Example 2: Seeing the worker threads (Java 9+)
Record which threads processed elements of a parallel stream.
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class WhichThreads {
public static void main(String[] args) {
Set<String> threads = ConcurrentHashMap.newKeySet();
IntStream.range(0, 2_000)
.parallel()
.forEach(i -> threads.add(Thread.currentThread().getName().replaceAll("\\d+$", "N")));
System.out.println("Threads used: " + threads);
}
}
Threads used: [ForkJoinPool.commonPool-worker-N, main]
On a single-core machine, or under special JVM settings, only main may appear. The set's printed order can also vary.
How it works: The calling thread, main, works alongside the common pool's workers (their numbers are replaced by N here). The thread-safe ConcurrentHashMap.newKeySet() is used because several threads add to it.
Example 3: Order-sensitive operations still give the same answer
Compare findFirst() and findAny() on the same parallel stream.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class OrderInParallel {
public static void main(String[] args) {
List<Integer> collected = IntStream.rangeClosed(1, 10).parallel()
.map(n -> n * n).boxed().collect(Collectors.toList());
int first = IntStream.rangeClosed(1, 100_000).parallel()
.filter(n -> n % 7_919 == 0).findFirst().getAsInt();
int any = IntStream.rangeClosed(1, 100_000).parallel()
.filter(n -> n % 7_919 == 0).findAny().getAsInt();
System.out.println("collect keeps order: " + collected);
System.out.println("findFirst: " + first);
System.out.println("findAny is a match: " + (any % 7_919 == 0));
}
}
collect keeps order: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] findFirst: 7919 findAny is a match: true
How it works: collect() and findFirst() respect encounter order even in parallel. findAny() may return any multiple of 7919, so the program only checks that it is a valid match.
Example 4: The common pool's parallelism
Print how many processors the JVM sees and the common pool's default parallelism.
import java.util.concurrent.ForkJoinPool;
public class PoolSize {
public static void main(String[] args) {
int cpus = Runtime.getRuntime().availableProcessors();
int parallelism = ForkJoinPool.commonPool().getParallelism();
System.out.println("Available processors: " + cpus);
System.out.println("Common pool parallelism: " + parallelism);
System.out.println("Parallelism = processors - 1? " + (parallelism == Math.max(1, cpus - 1)));
}
}
Available processors: 10 Common pool parallelism: 9 Parallelism = processors - 1? true
The first two numbers depend on the machine; the third line is true unless the parallelism property has been set.
How it works: By default the pool has one thread fewer than the number of processors, because the calling thread also does work.
4. Real-World Use Cases
- Batch analytics: aggregate millions of in-memory records, such as sales or sensor readings.
- CPU-heavy transformations: image thumbnails, encryption or scoring of independent items.
- Simulations: Monte Carlo runs where each sample is independent.
- Offline jobs: nightly reports on large data loaded into memory.
5. Important Points
- Same result: a correct pipeline gives the same answer sequentially and in parallel.
- Shared pool: all parallel streams in a JVM share the common
ForkJoinPool. - Overhead: splitting and combining cost time; small inputs are usually slower in parallel.
- Side effects in lambdas become race conditions.
- Order-sensitive operations such as
limit()andfindFirst()can reduce the speed-up. - Exceptions from worker threads are rethrown by the terminal operation.
6. Sequential vs Parallel at a Glance
| Aspect | Sequential stream | Parallel stream |
|---|---|---|
| Threads | Caller only | Caller plus common pool workers |
| Splitting | None | Spliterator splits the source |
| Result for correct code | Reference result | Same result |
Order of forEach() | Encounter order in practice | Unpredictable |
| Best for | Most code | Large, CPU-bound, independent work |
For a detailed comparison, see Stream vs Parallel Stream.
7. Common Mistakes and Best Practices
Expecting automatic speed-ups
Adding parallel() to a pipeline over 50 elements usually makes it slower. Measure before and after; see Sequential vs Parallel Performance.
Using non-thread-safe state
List<Integer> result = new ArrayList<>();
numbers.parallelStream().filter(n -> n > 0).forEach(result::add); // lost elements or exceptions
Return results with collect() or toList(); see Thread Safety.
Other mistakes to avoid
- Blocking I/O inside parallel lambdas, which starves the shared pool.
- Assuming order from
forEach()orfindAny(). - Using parallel streams inside web request threads by habit; many requests already run concurrently.
8. Summary
- A parallel stream splits its source and processes the parts on the common
ForkJoinPool. - Create one with
parallelStream()orparallel(). - Correct pipelines give the same results in both modes; order-sensitive operations still work.
- Parallelism has overhead and shared-state risks; measure and keep lambdas side-effect free.
9. References
Frequently Asked Questions (FAQ)
Q1. What is a parallel stream in Java?
A parallel stream is a stream whose operations are executed by multiple threads. The source is split into chunks, the chunks are processed on the common ForkJoinPool, and the partial results are combined.
Q2. How do I create a parallel stream?
Call parallelStream() on a collection, or parallel() on any existing stream, for example IntStream.range(0, n).parallel().
Q3. Which thread pool does a parallel stream use?
The common ForkJoinPool, returned by ForkJoinPool.commonPool(). Its default parallelism is the number of available processors minus one, and the calling thread also helps.
Q4. Do parallel streams give the same results as sequential streams?
For correct pipelines, yes. Results differ only when lambdas have side effects, functions are not associative, or nondeterministic operations such as forEach() or findAny() are used.
Q5. Are parallel streams always faster?
No. They help with large amounts of CPU-heavy, independent work on sources that split well. For small inputs or I/O-bound work they are often slower.