Stream confusion

Ron Pressler ron.pressler at oracle.com
Wed Nov 22 19:46:09 UTC 2023



> On 22 Nov 2023, at 17:52, Archie Cobbs <archie.cobbs at gmail.com> wrote:
> 
> To do that, I would have to assume (for example) that Stream.filter() will always execute in the current thread, because otherwise the writes to the non-final fields are not guaranteed to be visible to other threads.

I don’t think you need to assume that. *Which* writes you’re afraid may not be visible? All writes that “happen before” the call to the stream’s terminal operation should be visible regardless of which threads are used.

For example, you can generally submit tasks with non-final fields to ExecutorServices backed by thread pools because the writes to the fields on the submitting thread “happen before” the submission, and the submission “happens before” the execution of the task on the worker thread. Of course, you may get races if the submitting thread tries to mutate the fields after the submission of the task.

> 
> But this is not guaranteed to be true in the Stream API docs. In fact, they explicitly state that this would be an unsafe assumption: ...
> 

I think you’re reading “mutable state” as “non-final fields”, but the intent — as I read it — is "state that is mutated concurrently with the stream’s operation."

— Ron


More information about the amber-dev mailing list