Parallel Streams Summary
Parallel Processing Concept
- Concurrent execution of tasks
- Uses multiple threads/cores
- Automatic work distribution
- Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.parallelStream() .map(x -> x * 2) .collect(Collectors.toList());
Creating Parallel Streams
-
From Collection:
// Method 1 list.parallelStream() // Method 2 list.stream().parallel()
-
From Arrays:
Arrays.stream(array).parallel()
Parallel Stream Operations
-
Stateless Operations (Safe):
- map
- filter
- flatMap
stream.parallel() .filter(x -> x > 0) .map(x -> x * 2)
-
Stateful Operations (Careful):
- sorted
- distinct
- limit
stream.parallel() .sorted() // may impact performance .distinct() // requires coordination
Performance Considerations
-
When to Use:
- Large data sets
- Computationally intensive
- Independent operations
- Multiple cores available
-
When to Avoid:
- Small data sets
- IO-bound operations
- Operations with dependencies
- Single core systems
Thread Safety
-
Safe Operations:
// Thread-safe reduction int sum = numbers.parallelStream() .reduce(0, Integer::sum);
-
Unsafe Operations:
// Not thread-safe List<Integer> list = new ArrayList<>(); stream.parallel() .forEach(list::add); // Don't do this!
Best Practices
- Use thread-safe collections
- Avoid stateful operations
- Consider ordering requirements
- Test performance gains
- Handle exceptions properly
- Use appropriate collectors
- Example:
```java
// Good practice
List
result = numbers.parallelStream() .map(x -> expensiveOperation(x)) .collect(Collectors.toList());