nerdexam
Oracle

1Z0-829 · Question #3

Given the code fragment: ExecutorService executorService = Executors.newSingleThreadExecutor(); Set<Callable<String>> workers = new HashSet<Callable<String>>(); workers.add(new Callable<String>() {…

The correct answer is C. List<Future<String>> futures = executorService.invokeAll(workers); for(Future<String> future : futures){ System.out.println(future.get()); }. The code fragment in Option C invokes all callable objects in the workers set by using the ExecutorService's invokeAll() method. This method takes a collection of Callable objects and returns a List of Future objects representing the results of the tasks. The other options are…

Managing concurrent code execution

Question

Given the code fragment: ExecutorService executorService = Executors.newSingleThreadExecutor(); Set<Callable<String>> workers = new HashSet<Callable<String>>(); workers.add(new Callable<String>() { public String call() throws Exception { return "1"; } }); workers.add(new Callable<String>() { public String call() throws Exception { return "2"; } }); workers.add(new Callable<String>() { public String call() throws Exception { return "3"; } }); Which code fragment invokes all callable objects in the workers set?

Options

  • AList<Future<String>> futures = executorService.invokeAny(workers); for(Future<String> future : futures){ System.out.println(future.get()); }
  • BexecutorService.submit(cThreads);
  • CList<Future<String>> futures = executorService.invokeAll(workers); for(Future<String> future : futures){ System.out.println(future.get()); }
  • Dfor (int i=0; i<3;i++){ String result = executorService.invokeAny(cThreads); System.out.println(result); }

How the community answered

(33 responses)
  • B
    3% (1)
  • C
    94% (31)
  • D
    3% (1)

Explanation

The code fragment in Option C invokes all callable objects in the workers set by using the ExecutorService's invokeAll() method. This method takes a collection of Callable objects and returns a List of Future objects representing the results of the tasks. The other options are incorrect because they either use the wrong method (invokeAny() or submit()) or have syntax errors (missing parentheses or semicolons). Reference: AbstractExecutorService (Java SE 17 & JDK 17) - Oracle

Topics

#ExecutorService#invokeAll#Callable#Future

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice