admin wrote:Just change the call to parallelStream to stream and you will see that it will print _ab. Now, the point is that even when you use parallelStream, there is no guarantee that elements will be processed in parallel. If you have a single core machine, it is possible that you get a serial stream.
That is why you cannot guarantee that the result will always be _a_b.
HTH,
Paul.
I still don't understand how it could return _ab.
I am trying to differentiate between two things:
1. Processing a parallel stream in a sequential manner (no matter how many threads are available)
2. Processing a parallel stream using a single thread (which follows different steps than those of a sequential operation)
In other words, I am trying not to confuse a "
sequential operation" with a"
parallel operation with a single thread". In the case of
reduce() for example, I believe that in case of a parallel stream the
identity is accumulated with every element first producing intermediate results, then the combiner combines those results to produce the final output. This has nothing to do with the number of threads available,
parallel evaluation follows different steps in the first place. Even if there is only on thread, it will follow the same steps (that is, compute the intermediate accumulations then combine them). On the other hand, in case of a sequential stream,
reduce() follows a different logic; it doesn't invoke the combiner at all (since there are no intermediate results). Both parallel and sequential reductions are supposed to give the same output, provided some criteria are met (which is not the case in this question).
To verify such point, I changed the example given in the explanation of the question to use a custom ForkJoinPool
with only one thread to process the parallel stream (
ForkJoinPool.commonPool() is used by parallel streams). It gave me an output consistent with my point. The code is in the following post due to the character count limit.