below is a question from concurrency chapter in Boyarsky ocp book . The answer is C with this reasoning "as the output of submit(Runnable) task is a Future<?> object which can
only return null on its get() method."
Why can it not be a callable (service.submit(() -> counter++ as it returns a value
What is the result of executing the following program?
A. It prints 0 1 2 3 4
B. It prints 1 2 3 4 5
C. It prints null null null null null
First of all, when you post a code snippet, please make sure it is formatted properly (indentation, etc). You can always check what your code will look like using the preview button.
The submit() method accept a Runnable but an overloaded version also accepts a Callable. The difference between a Runnable and a Callable is that a Callable returns something and also supports checked exception. So when you pass this lambda:
it augments the static counter variable by one but it doesn't return anything. Therefore, Java considers the lambda as a Runnable, rather than a Callable. Since a Runnable does not return anything, the Future<?> object does not contain any result. A Future object represents the result of an asynchronous computation. Calling get() on such an object will return null.