Hi @core-libs-dev,

I am looking to validate the following idiom:

Stream.iterate(seed, e -> e.nextOrNull())
    .takeWhile(Objects::nonNull);

The intent is for the stream to call nextOrNull() repeatedly until it
returns null. However, I am concerned about where the Stream specification
guarantees the correctness of this approach regarding happens-before
relationships.

The iterate() Javadoc defines happens-before for the function passed to it,
stating that the action of applying f for one element happens-before the
action of applying it for subsequent elements. However, it seems silent on
the happens-before relationship with downstream operations like takeWhile().

My concern stems from the general discouragement of side effects in stream
operations. For example, relying on side effects between subsequent map()
calls is considered brittle because a stream might invoke the first map()
on multiple elements before the second map() processes the first element.

If this theory holds, is there anything theoretically preventing iterate()
from generating multiple elements before takeWhile() evaluates the first
one? I may be overthinking this, but I would appreciate your insights into
why side effects are discouraged even in ordered, sequential streams and
whether this specific idiom is safe.

Appreciate your help!

Best regards,
Jige Yu

Reply via email to