After going through the following answers which talks about using concurrent data structures in streams and different between using concurrent map and converting to a map, can someone explain what will happen if I am using the other syntax of collect
i.e.
Stream<Integer> integers = Stream.iterate(1, n -> n + 1).parallel();
Map<Integer, Boolean> resultMap = integers
.limit(1000)
.collect(HashMap::new,
(map, value) -> map.put(value, false),
HashMap::putAll);
As per the documentation, supplier will be invoked depending on number of threads spawned. What if i use ConcurrentHashMap
instead of HashMap
?
When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.