Given the following code snippet, which lambda expression is the best choice for the accumulator, based on the rules for applying a parallel reduction?.
public class Main { int i; public void test() { BiFunction<Integer,Integer,Integer> accumulator = ___; System.out.print(Arrays.asList(1,2,3,4,5) .parallelStream() .reduce(0,accumulator,(s1, s2) -> s1 + s2)); } }
B.
An accumulator in a serial or parallel reduction must be associative and stateless.
In a parallel reduction, invalid accumulators tend to produce more visible errors, where the result may be processed in an unexpected order.
Option A is not associative, since (a-b)-c is not the same as a-(b-c) for all values a, b, and c.
Using values of 1, 2, and 3 results in two different values, -4 and 2.
Option C is not stateless, since a class or instance variable i is modified each time the accumulator runs.
That leaves us with Option B, which is the correct answer since it is both stateless and associative.
Even though it ignores the input parameters, it meets the qualifications for performing a reduction.