posted 6 years ago
The question is:
What is the result of executing the following program?
Answer options:
A. It prints 0 1 2 3 4
B. It prints 1 2 3 4 5
C. It prints null null null null null
D. It hangs indefinitely at runtime.
E. The output cannot be determined.
F. The code will not compile because of line n1.
G. The code will not compile because of line n2.
The correct answer is:
F. The key to solving this question is to remember that the execute() method returns
void, not a Future object. Therefore, line n1 does not compile and F is the correct answer.
If the submit() method had been used instead of execute(), then C would have been the
correct answer, as the output of submit(Runnable) task is a Future<?> object which can
only return null on its get() method.
I'm absolutely agreed with the answer as I answer it the same. What is confuses me is a propagated alternative: in case of using of submit() method, passed lambda expression () -> counter++ would be evaluated as pure Callable not Runnable (in fact this lambda can also be evaluated as Runnable due to compiler contract, the same as Function lambda can be evaluated as Consumer if required) and program will end up with the answer A.