00:00

Parallel Streams in Java: An Introduction

Last updated:

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

API overview
// 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.

Split, process and combine in a parallel stream The source is split by its Spliterator into chunks. Worker threads of the common ForkJoinPool, plus the calling thread, process the chunks through the pipeline at the same time. Partial results are combined into the final result in the order the operation requires. Spliteratorsplit source SPLIT forkchunk tasks processworker threads joincombine parts resultsame answer RESULT FORK / JOIN
Figure 1: A parallel stream divides the source, runs the pipeline on each part in a different thread, and merges the partial results.

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.

FirstParallelStream.java
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);
    }
}
Output
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.

WhichThreads.java
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);
    }
}
Output
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.

OrderInParallel.java
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));
    }
}
Output
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.

PoolSize.java
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)));
    }
}
Output
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() and findFirst() can reduce the speed-up.
  • Exceptions from worker threads are rethrown by the terminal operation.

6. Sequential vs Parallel at a Glance

AspectSequential streamParallel stream
ThreadsCaller onlyCaller plus common pool workers
SplittingNoneSpliterator splits the source
Result for correct codeReference resultSame result
Order of forEach()Encounter order in practiceUnpredictable
Best forMost codeLarge, 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

Wrong
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() or findAny().
  • 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() or parallel().
  • 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