Parallel Stream
Parallel Stream:
A Parallel Stream in Java is a type of stream that processes elements
concurrently using multiple threads, leveraging multi-core processors to
improve performance. It is part of the Java Stream API and is built on the
Fork/Join framework.
➢ Divides the stream into multiple parts and processes them simultaneously.
➢ Uses multiple threads to execute operations in parallel.
➢ Can be created using:
1. [Link]() – Creates a parallel stream from a collection.
2. [Link]() – Converts a sequential stream into a parallel stream.
➢ Order of execution is not guaranteed due to concurrent processing.
➢ May improve performance for large datasets but may have overhead for small
collections.
➢ Not thread-safe for shared mutable state, requiring synchronization in such cases.
When to Use Parallel Streams?
When working with large datasets for better performance.
When operations are independent and do not require ordering.
When CPU-intensive tasks need to be distributed across multiple cores.
Note:
• Avoid parallel stream when processing small datasets.
• Avoid parallel when order of execution is important .
• Avoid parallel when working with shared mutable state, as parallel execution may
cause race
Example:
Output:
Note:
The output will be depend on system performance.