How many threads will open for parallel streams and how does parallel stream internally work?

Parallel Streams use the ForkJoin Framework to process data concurrently across multiple threads. By default, they utilize the common ForkJoinPool, whose parallelism level is typically equal to the number of available processor cores minus one. The stream automatically divides the data into smaller tasks, executes them in parallel, and then combines the results to produce the final output.

Key Points: • Parallel Streams use ForkJoinPool.commonPool() unless a custom ForkJoinPool is explicitly provided. • The default number of worker threads is usually equal to Runtime.getRuntime().availableProcessors() - 1. • Internally, data is split into subtasks, processed by multiple threads using work-stealing, and merged into a final result.

Internal Working:

1. Data Splitting • The source collection is divided into smaller chunks using a Spliterator.

2. Task Distribution • Each chunk is assigned to worker threads in the ForkJoinPool.

3. Parallel Processing • Multiple threads process chunks simultaneously.

4. Work Stealing • If a thread finishes early, it can "steal" tasks from busy threads to improve CPU utilization.

5. Result Merging • Partial results from all threads are combined into the final output.

Thread Calculation Example:

If the machine has:

Runtime.getRuntime().availableProcessors() = 8

Then the common ForkJoinPool typically creates:

Parallelism = 8 - 1 = 7 worker threads

Note: The calling thread may also participate in execution, so you may observe more than 7 threads involved in processing.

Example: Suppose you need to process one million transactions. A parallel stream automatically divides the collection into multiple chunks and distributes them across CPU cores, significantly reducing execution time compared to sequential processing.

Code Example:

import java.util.List;

public class ParallelStreamDemo {

    public static void main(String[] args) {

        List<Integer> numbers =
                List.of(1, 2, 3, 4, 5, 6, 7, 8);

        numbers.parallelStream()
               .forEach(number -> {

                   System.out.println(

number + " : " +

                           Thread.currentThread()
                                 .getName());
               });
    }
}

Interview Tip: A concise interview answer is: Parallel Streams use the ForkJoinPool common pool to execute tasks concurrently. By default, the pool size is usually equal to the number of available CPU cores minus one. Internally, the stream uses a Spliterator to divide data into smaller tasks, processes them in parallel using work-stealing, and combines the results efficiently.