What is the result of executing the following program?
import java.util.*; import java.util.concurrent.*; import java.util.stream.*; public class Main { static int counter = 0; public static void main(String[] args) throws InterruptedException, ExecutionException { // w w w . j a va 2 s . com ExecutorService service = Executors.newSingleThreadExecutor(); List<Future<?>> results = new ArrayList<>(); IntStream.iterate(0,i -> i+1).limit(5).forEach( i -> results.add(service.execute(() -> counter++)) // n1 ); for(Future<?> result : results) { System.out.print(result.get()+" "); // n2 } service.shutdown(); } }
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.