Video in progress
Why can limit(), skip() and findFirst() be slow in parallel mode on an ordered stream?
On an ordered stream, "the first 10" means the first 10 in source order. In parallel each thread works on its own chunk, so to determine which elements really come first, the framework has to buffer results and wait for the earlier chunks. That is extra memory and synchronization.
📖 Answer
List<Integer> firstTen = IntStream.range(0, 50_000_000).boxed()
.parallel()
.filter(this::isInteresting)
.limit(10)
.toList();
This code can run even slower than the sequential version. Threads that got chunks on the right find many elements, but can't emit them until the chunk on the left is finished, so they sit in a buffer. skip is the same.
If "any 10" is enough for you, relax the ordering:
.parallel()
.unordered()
.filter(this::isInteresting)
.limit(10)
.toList();
Using findAny instead of findFirst is the same idea: once the ordering requirement is gone, parallelism pays off.
A stream taken from an unordered source such as a HashSet is already unordered, and has this problem less.
The practical takeaway: before turning on a parallel stream, check whether the chain has limit, skip, findFirst, forEachOrdered or sorted. They eat much of the parallelism. I don't decide to parallelize such a chain without a JMH measurement.
Sign up to mark studied questions and save your progress.