Executors and thread pools question 86 of 180 mid
What is invokeAll versus invokeAny, and where does CompletionService fit?
invokeAllruns tasks one by one- Correct:
invokeAllblocks until all finish and returns futures in submission order;invokeAnyreturns the first success and cancels the rest;CompletionServiceyields results as they complete invokeAnyreturns the fastest task's future without running the others- They all require a
ScheduledExecutorService
invokeAll submits a batch and blocks until every task is done (or the timeout expires), returning
futures in the order of the input, all of them already complete. invokeAny is the racing variant: the
first task to return normally wins, its value is returned, and the others are cancelled.
Neither helps when you want to process results in completion order rather than submission order, and
writing that with Future.get() in a loop wastes time on a slow first element.
ExecutorCompletionService solves it: it pushes each finished task onto a queue you take() from, so
you always handle whatever is ready.
In modern code CompletableFuture.allOf / anyOf covers the same ground non-blockingly, and
StructuredTaskScope covers it with cancellation built in.
Quiz yourself on Executors and thread pools Suggest a correction