Skip to main content

Lesson 6 of 8

Parallel Streams

Parallel streams split work across CPU cores using the ForkJoin common pool. They can dramatically speed up CPU-intensive operations on large datasets - but they also introduce pitfalls around ordering, thread safety, and overhead, making them unsuitable for many common scenarios.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Parallel Streams - When & How

Parallel Streams - When & How
import java.util.*;
import java.util.stream.*;

public class ParallelStreams {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000)
                                         .boxed()
                                         .collect(Collectors.toList());

        // Sequential
        long startSeq = System.nanoTime();
        long sumSeq = numbers.stream()
                             .mapToLong(Integer::longValue)
                             .sum();
        long timeSeq = System.nanoTime() - startSeq;

        // Parallel - just add .parallel()
        long startPar = System.nanoTime();
        long sumPar = numbers.parallelStream()       // or .stream().parallel()
                             .mapToLong(Integer::longValue)
                             .sum();
        long timePar = System.nanoTime() - startPar;

        System.out.printf("Sequential: %dms%n", timeSeq / 1_000_000);
        System.out.printf("Parallel:   %dms%n", timePar / 1_000_000);
        System.out.println("Results match: " + (sumSeq == sumPar));

        // Parallel ordering - findFirst is deterministic, findAny is not
        Optional<Integer> first = numbers.parallelStream()
            .filter(n -> n % 7 == 0)
            .findFirst();    // still returns the FIRST matching element (ordered)

        // Force ordering with .sorted() or .forEachOrdered()
        numbers.parallelStream()
               .filter(n -> n % 100_000 == 0)
               .sorted()
               .forEachOrdered(System.out::println);   // guaranteed order

        // ❌ ANTI-PATTERNS:
        // Do NOT use shared mutable state
        List<Integer> results = new ArrayList<>();
        numbers.parallelStream()
               .filter(n -> n % 2 == 0)
               .forEach(results::add);  // RACE CONDITION - ArrayList not thread-safe!

        // ✅ Use collect instead
        List<Integer> safeResults = numbers.parallelStream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());  // thread-safe via Collector

        // ThreadLocalRandom - parallel-safe random
        double avg = IntStream.range(0, 1_000_000)
            .parallel()
            .mapToDouble(i -> java.util.concurrent.ThreadLocalRandom.current().nextDouble())
            .average().orElse(0.0);
    }
}

When to Use Parallel Streams

  • ✅ Large datasets (100k+ elements) with CPU-intensive operations (complex calculations, string processing).
  • ✅ Operations that are naturally independent - no shared mutable state.
  • ✅ Operations where order doesn't matter, or you explicitly handle ordering.
  • ❌ Small collections - thread overhead exceeds the speedup.
  • ❌ I/O-bound operations (file reads, DB queries) - blocked threads waste parallelism.
  • ❌ Operations with shared mutable state - race conditions without synchronisation.
  • ❌ Ordered terminal operations on short-circuit streams - parallel doesn't help findFirst.

Quick Quiz

Tip

Tip

Practice Parallel Streams in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Parallel Streams

Practice Task

Note

Practice Task - (1) Write a working example of Parallel Streams from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Parallel Streams is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Key Takeaways

  • Parallel streams split work across CPU cores using the ForkJoin common pool.
  • ✅ Large datasets (100k+ elements) with CPU-intensive operations (complex calculations, string processing).
  • ✅ Operations that are naturally independent - no shared mutable state.
  • ✅ Operations where order doesn't matter, or you explicitly handle ordering.

Topics in This Module

0/8 done