Aprel
Aprel

Reputation: 514

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

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?

Upvotes: 3

Views: 1324

Answers (1)

Aprel
Aprel

Reputation: 514

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.

Upvotes: 6

Related Questions