Non-interference exact meaning in Java 8 streams

There’s a bigger class of functions called “functions with side effects”. The JavaDoc statement is correct and complete: here interference means modifying the mutable source. Another case is stateful expressions: expressions which depend on the application state or change this state. You may read the Parallelism tutorial on Oracle site.

In general you can modify the stream elements themselves and it should not be called as “interference”. Beware though if you have the same mutable object produced several times by the stream source (for example, using Collections.nCopies(10, new MyMutableObject()).parallelStream(). While it’s ensured that the same stream element is not processed concurrently by several threads, if your stream produces the same element twice, you may surely have a race condition when modifying it in the forEach, for example.

So while stateful expressions are sometimes smell and should be used with care and avoided if there’s a stateless alternative, they are probably ok if they don’t interfere with the stream source. When the stateless expression is required (for example, in Stream.map method), it’s specially mentioned in the API docs. In forEach documentation only non-interference is required.

So back to your questions:

Question 1: no we can change the element state, and it’s not called interference (though called statefullness)

Question 2: no it has no interference unless you have repeating objects in your stream source)

Question 3: you can safely use parallelStream() there

Question 4: no, you can use Stream API in this case.

Leave a Comment