Does the specification guarantee, that all operations on sequential Java Streams are executed in the current thread? (Except for "forEach" and "forEachOrdered")
I explicitly ask for the specification, not what the current implementation does. I can look into the current implementation myself and don't need to bother you with that. But the implementation might change and there are other implementations.
I'm asking because of ThreadLocals: I use a Framework which uses ThreadLocals internally. Even a simple call like company.getName() eventually uses a ThreadLocal. I cannot change how that framework is designed. At least not within a sane amount of time.
The specification seems confusing here. The documentation of the Package "java.util.stream" states:
If the behavioral parameters do have side-effects, unless explicitly stated, there are no guarantees as to the visibility of those side-effects to other threads, nor are there any guarantees that different operations on the "same" element within the same stream pipeline are executed in the same thread.
...
Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example, IntStream.range(0,5).parallel().map(x -> x*2).toArray() must produce [0, 2, 4, 6, 8]), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.
I would interpret that as: Every operation on a stream can happen in a different thread. But the documentation of "forEach" and "forEachOrdered" explicitly states:
For any given element, the action may be performed at whatever time and in whatever thread the library chooses.
That statement would be redundant if every stream operation could happen in an unspecified thread. Is therefore the opposite true: All operations on a serial stream are guaranteed to be executed in the current thread, except for "forEach" and "forEachOrdered"?
I have googled for an authoritative answer about the combination of "Java", "Stream" and "ThreadLocal" but found nothing. The closes thing was an answer by Brian Goetz to a related question here on Stack Overflow, but it is about the order, not the thread, and it is only about "forEach", not the other stream methods: Does Stream.forEach respect the encounter order of sequential streams?