CompletionService Interface in Java: Process Results as They Finish
When you submit many tasks, invokeAll() and a loop over futures return results in submission order, so one slow task holds up everything after it. A CompletionService hands results back in the order the tasks finish.
This tutorial explains the interface, its standard implementation ExecutorCompletionService, and two practical patterns.
1. What Is CompletionService?
CompletionService<V> is an interface in java.util.concurrent, added in Java 5. It separates producing results from consuming them: one side submits tasks, the other side takes completed futures as they become available.
The JDK provides one implementation, ExecutorCompletionService. It runs tasks on an Executor you supply and puts each finished task's Future into a BlockingQueue.
2. CompletionService Hierarchy
Swipe sideways to see the whole diagram.
ExecutorCompletionService(class): The standard implementation; it wraps an existing executor.Executor(interface): Does the actual work; any executor or thread pool can be used.BlockingQueue<Future<V>>(interface): Holds completed futures untiltake()orpoll()removes them.
3. Method Details
| Method | Description |
|---|---|
submit(Callable<V>) | Submits a task; its Future is queued when the task completes. |
submit(Runnable, V result) | Same, with a fixed result value. |
take() | Waits for, then removes, the next completed Future. |
poll() | Removes the next completed Future, or returns null if none is ready. |
poll(timeout, unit) | Waits up to the timeout; returns null if nothing completes. |
4. Example: Rendering Report Sections as They Finish
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ReportSections {
static String render(String section, long millis) throws InterruptedException {
Thread.sleep(millis);
return section + " (" + millis + " ms)";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
CompletionService<String> sections = new ExecutorCompletionService<>(pool);
// Submitted in page order...
sections.submit(() -> render("Revenue chart", 600));
sections.submit(() -> render("Summary text", 200));
sections.submit(() -> render("Customer table", 400));
// ...but take() hands them back in the order they finish
for (int i = 1; i <= 3; i++) {
Future<String> done = sections.take();
System.out.println("ready #" + i + ": " + done.get());
}
}
}
}
ready #1: Summary text (200 ms) ready #2: Customer table (400 ms) ready #3: Revenue chart (600 ms)
How the code works
ExecutorCompletionServicewraps a three-thread pool, so all sections render at the same time.- The tasks are submitted in page order, but they take 600, 200 and 400 ms.
- Each
take()blocks until the next task finishes, so the summary is ready first and the chart last. - The
Futurereturned bytake()is already complete, soget()returns immediately.
5. Example: Using Only the First Two Answers
A comparison site asks four insurers for a quote and shows the customer the first two that reply.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FirstTwoQuotes {
record Quote(String insurer, int premium) {}
static Quote ask(String insurer, int premium, long millis) throws InterruptedException {
Thread.sleep(millis);
return new Quote(insurer, premium);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
CompletionService<Quote> quotes = new ExecutorCompletionService<>(pool);
List<Future<Quote>> pending = new ArrayList<>();
pending.add(quotes.submit(() -> ask("Harbor Mutual", 412, 900)));
pending.add(quotes.submit(() -> ask("Northline", 389, 150)));
pending.add(quotes.submit(() -> ask("Evergreen", 455, 350)));
pending.add(quotes.submit(() -> ask("Summit Re", 398, 1_500)));
// Show the customer the first two answers, then stop waiting for the rest
for (int i = 0; i < 2; i++) {
Quote q = quotes.take().get();
System.out.println(q.insurer() + ": " + q.premium() + " EUR/year");
}
pending.forEach(f -> f.cancel(true)); // no effect on tasks that already finished
System.out.println("Remaining requests cancelled");
}
}
}
Northline: 389 EUR/year Evergreen: 455 EUR/year Remaining requests cancelled
How the code works
- All four requests start immediately; the futures returned by
submit()are kept in a list. - Two
take()calls return the two fastest replies, from Northline and Evergreen. cancel(true)then interrupts the requests that are still waiting; it has no effect on those that already finished.
6. CompletionService vs invokeAll()
invokeAll() | CompletionService | |
|---|---|---|
| Result order | Submission order | Completion order |
| Returns when | All tasks are done | Each take() returns as soon as one more task is done |
| Best for | Needing every result together | Processing results early, or stopping after the first few |
7. Common Mistakes and Best Practices
- Calling
take()too often. Call it exactly once per submitted task; an extra call blocks forever. - Forgetting the executor. The completion service does not own the executor; shut the executor down yourself.
- Ignoring failures. A failed task still arrives through
take(); itsget()throwsExecutionException. - Use
poll(timeout, unit)for deadlines. It lets you stop waiting when time runs out instead of blocking.
8. Summary
CompletionServicereturns task results in completion order, not submission order.ExecutorCompletionServicewraps anyExecutorand queues completed futures.take()waits for the next result;poll()returnsnullif none is ready.- It is ideal for processing results early or keeping only the first few.
Related Tutorials
9. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between CompletionService and ExecutorService?
An ExecutorService runs tasks and manages threads. A CompletionService sits on top of an executor and gives you completed results in the order they finish, through take() and poll().
Q2. Does ExecutorCompletionService shut down the executor?
No. It has no lifecycle methods. You must shut down the underlying executor yourself, for example with try-with-resources.
Q3. What happens if a task submitted to a CompletionService fails?
Its Future is still placed in the completion queue. When you take it, get() throws ExecutionException with the task's exception as the cause.
Q4. What is the difference between take() and poll()?
take() blocks until a completed task is available. poll() returns immediately, with null if nothing has completed, and poll(timeout, unit) waits only up to the given time.
Q5. Can I use CompletionService with virtual threads?
Yes. Pass any executor to the constructor, for example new ExecutorCompletionService<>(Executors.newVirtualThreadPerTaskExecutor()) on Java 21 or later.