Does Stream.forEach () always work in parallel?

In Stream Aggregation, Brian Goetz compares the collection fill with Stream.collect () and does the same with Stream.forEach (), with the following two snippets:

Set<String> uniqueStrings = strings.stream()
                                   .collect(HashSet::new,
                                            HashSet::add,
                                            HashSet::addAll);

and

Set<String> set = new HashSet<>();
strings.stream().forEach(s -> set.add(s));

He then explains:

The key difference is that with the version forEach () several threads try to access the same container result at the same time, while with parallel collect () each thread has its own local container result, the results of which are then merged.

As far as I understand, several threads will work in the case of forEach () only if the thread is parallel. However, in the above example, forEach () works in a serial stream (there is no call to the parallelStream () function).

, forEach() parallelStream() stream(). ( - ?)

+4
2

, forEach() , . , .

AbstractPipeline ( forEach)

 return isParallel()
               ? terminalOp.evaluateParallel(this, sourceSpliterator(terminalOp.getOpFlags()))
               : terminalOp.evaluateSequential(this, sourceSpliterator(terminalOp.getOpFlags()));
+5

:

, , , Stream.collect() , ( collect()).

, :

, forEach() , collect() , .

, , forEach(), collect() .

+1

Source: https://habr.com/ru/post/1667458/


All Articles