Video in progress
When do you need groupingByConcurrent() instead of groupingBy() on a parallel stream, and what does unordered() give you?
A parallel groupingBy builds a separate map for each chunk and then merges them, and with many keys the merge is expensive. groupingByConcurrent uses one ConcurrentHashMap that all threads write to and removes the merge, but order within a group isn't guaranteed.
📖 Answer
ConcurrentMap<String, Long> hits = logLines.parallelStream()
.unordered()
.collect(Collectors.groupingByConcurrent(Line::endpoint, Collectors.counting()));
How it works:
groupingByin parallel: N chunks, NHashMaps. The combiner merges each pair of maps by key. With 1 million unique keys, that merging can eat most of the time.groupingByConcurrent: the collector has theCONCURRENTandUNORDEREDflags. Because the collector itself isUNORDERED, the framework uses one shared container even if the source is ordered, and the combiner isn't called.
unordered() isn't a strict requirement here, but it states the intent openly. The rule is this: concurrent collection is used only if the stream is parallel and (the stream is unordered or the collector is UNORDERED). With a collector you wrote yourself that is CONCURRENT but not UNORDERED, if you don't call unordered() on an ordered source such as an ArrayList, the framework falls back to ordinary reduction. unordered() doesn't shuffle the data: it only tells the stream "order doesn't matter to me". It also makes distinct() and limit() cheaper in parallel.
When you don't need it: on a sequential stream there's no gain, only the cost of ConcurrentHashMap. Also when the order of the list within a group matters.
Measure before choosing between the two. In many cases the number of keys is small (a few dozen statuses, cities) and a plain groupingBy is enough.
Sign up to mark studied questions and save your progress.