0Pricing
Java Academy · Lesson

When Parallelism Helps

Workload and data size factors.

Parallelism Has a Cost

Going parallel adds overhead: splitting data, dispatching tasks, and merging results. It only pays off when that cost is smaller than the time saved.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        long sum = IntStream.rangeClosed(1, 10_000_000)
            .parallel()
            .asLongStream()
            .sum();
        System.out.println(sum);
    }
}

Factor 1: Data Size (N)

Large N amortizes the fixed overhead of parallelism. A rough rule of thumb is tens of thousands of elements before parallel becomes worthwhile.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        long count = IntStream.rangeClosed(1, 5_000_000)
            .parallel()
            .filter(n -> n % 7 == 0)
            .count();
        System.out.println(count);
    }
}

All lessons in this course

  1. Creating Parallel Streams
  2. When Parallelism Helps
  3. Thread Safety and Side Effects
  4. Common Pitfalls
← Back to Java Academy