Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java 8 parallel Streams, do terminal operations finish all computation before returning?

Tags:

java

java-8

For example, if class Foo has instance method bar(),

List<Foo> list = new ArrayList<>();
// ...
list.stream()
    .parallel()
    .forEach(Foo::bar);
doSomething();

Is it guaranteed that all calls to bar() have returned before doSomething() is called?

like image 747
Aprel Avatar asked Mar 03 '26 11:03

Aprel


1 Answers

Yes, except for when the terminal operation is either iterator() or spliterator().

From the java.util.stream package page:

In almost all cases, terminal operations are eager, completing their traversal of the data source and processing of the pipeline before returning. Only the terminal operations iterator() and spliterator() are not; these are provided as an "escape hatch" to enable arbitrary client-controlled pipeline traversals in the event that the existing operations are not sufficient to the task.

like image 66
Aprel Avatar answered Mar 06 '26 01:03

Aprel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!