Hi,
While doing the practice tests I have run into a couple of questions so far for which I do not agree with their solutions: Chapter 6 Question 34 option B; and Chapter 6 Question 41 option B.
For both questions
to seem to be ok the parallel execution plan for the accumulation operation must satisfy that all threads are run on single-element chunks throughout the entire stream which, I must admit, seems to be the case when I have tested them as they are without introducing any change. As far as I know, there is no such warranty made by the
Java Language Specification and in any case would be incoherent to do so because the serial execution model would yield a different result. Therefore, I take for granted that it is just a coincidence that at least they may seem to work fine because the two streams are pretty small, much smaller than the
thread pool.
Anyway, if we look at the following
test cases for Q.34 and option B it seems quite easy to figure out that the reduction operation can be solved by applying N * 5 where N is the length of the stream. That is exactly what we expect to see if the accumulator function has been applied one by one so that we end up combining as many intermediate results as elements are in the stream. The accumulator function would behave just as a transformation function which ignores any previous result.
The first setback is that it is
not coherent with the serial execution model as the next test case shows.
The second setback is that it is
not consistent either once the parallelism threshold is exceeded as the next test case shows.
I also guess all these outputs depend on what JVM runtime implementation is used by the way.
The reduce method we are using states that the following condition must hold true for any accumulated 'u' value and stream element 't':
combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
In this case we have that:
identity = 0
accumulator = (a, b) -> K
combiner = (a, b) -> a + b
Then if we replace we get:
u + K = K
Of course this condition can only be true for any
u when
K = 0, and in turn, will make that
u = 0 as well because
0 + 0 = 0. But in option B it happens that
K = 5.