🚨 Parallel Streams are not always your friend 🚨
Parallel streams in Java look tempting.
More cores. More threads. Faster execution… right?
Not always.
Recently, I ran into a production issue that reminded me why parallelStream() needs extra care.
⚠️ ArrayList + parallelStream() = risky
ArrayList is not thread-safe.
When multiple threads add elements at the same time, things can break.
What I observed:
❌ Missing elements
❌ Inconsistent list size
❌ Occasional ArrayIndexOutOfBoundsException
🧠 What actually goes wrong (see diagram)
Multiple threads read the same internal size
All try to write at the same index
One thread resizes the array while others keep writing
💥 Race condition → corrupted state → exception
✅ Better approaches
Avoid shared mutable state:
List<Result> results = items.parallelStream().map(this::process).toList();
Or simply:
items.stream().map(this::process).toList();
💡 Takeaway
Parallel streams are powerful, but:
❌ Unsafe with ArrayList mutation
❌ Easy to misuse, hard to debug
❌ Not always faster
Parallelism is a tool, not a default choice.
Sometimes, boring and sequential wins.
#Java #ParallelStreams #Concurrency #ArrayList #RaceCondition #Performance #LessonsLearned
Even Squares and Odd Cubes with Java 8 Streams int[] arr= {1,2,3,4,5}; Map<Boolean, List<Integer>> evensSquaredAndOddCubes =Arrays.stream(arr).boxed().collect(Collectors.partitioningBy(n->n%2==0, Collectors.mapping(n->n%2==0 ? n*n : n*n*n, Collectors.toList()))); System.out.println("Even Numbers squers "+evensSquaredAndOddCubes.get(true)); System.out.println("Odd Numders qubes "+evensSquaredAndOddCubes.get(false));