Thread Safety and Side Effects
Avoid shared mutable state.
Parallel Means Concurrent Access
In a parallel stream, multiple threads run your lambdas at the same time. Any shared mutable state they touch becomes a race condition.
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int safe = IntStream.rangeClosed(1, 1000).parallel().sum();
System.out.println(safe);
}
}The Danger: Mutating a Shared Variable
A plain int counter touched by many threads loses updates. Never accumulate into shared mutable state inside forEach.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger();
IntStream.rangeClosed(1, 1000).parallel()
.forEach(n -> counter.incrementAndGet());
System.out.println(counter.get());
}
}All lessons in this course
- Creating Parallel Streams
- When Parallelism Helps
- Thread Safety and Side Effects
- Common Pitfalls