Junior — Middle
Explain the concept of parallel streams in Stream API and their features.
sobes.tech AI
Answer from AI
In Java Stream API, parallel streams allow operations on collection elements to be performed concurrently in multiple threads, which can improve performance on multi-core processors.
Features of parallel streams:
- Automatic data splitting: Stream divides the source data into parts processed in parallel.
- Use of ForkJoinPool: By default, parallel streams use a common ForkJoinPool to manage threads.
- Processing order: Parallel streams do not guarantee the preservation of element order unless specific methods (e.g.,
forEachOrdered) are used. - Side effects: It is important that operations are side-effect-free and thread-safe, otherwise the result may be unpredictable.
- Not always faster: Parallelism is beneficial with large data volumes and resource-intensive operations; for small datasets, overhead may outweigh benefits.
Example of creating a parallel stream:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
Here, the mapToInt and sum operations are performed in parallel if it is efficient.