00:00

CompletionService Interface in Java: Process Results as They Finish

Last updated:

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

CompletionService interface hierarchyExecutorCompletionService implements CompletionService. It runs tasks on an Executor and stores completed futures in a BlockingQueue.«interface»CompletionService<V>this pagesubmit(Callable), submit(Runnable, V)take(), poll(), poll(timeout, unit)«class»ExecutorCompletionService<V>new …(Executor)new …(Executor, BlockingQueue)«interface»Executorexecute(Runnable)«interface»BlockingQueue<Future<V>>completed tasksruns tasks onstores results inimplementsuses / createsinterfaceclass

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 until take() or poll() removes them.

3. Method Details

MethodDescription
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

ReportSections.java
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());
            }
        }
    }
}
Output
ready #1: Summary text (200 ms)
ready #2: Customer table (400 ms)
ready #3: Revenue chart (600 ms)

How the code works

  1. ExecutorCompletionService wraps a three-thread pool, so all sections render at the same time.
  2. The tasks are submitted in page order, but they take 600, 200 and 400 ms.
  3. Each take() blocks until the next task finishes, so the summary is ready first and the chart last.
  4. The Future returned by take() is already complete, so get() 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.

FirstTwoQuotes.java
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");
        }
    }
}
Output
Northline: 389 EUR/year
Evergreen: 455 EUR/year
Remaining requests cancelled

How the code works

  1. All four requests start immediately; the futures returned by submit() are kept in a list.
  2. Two take() calls return the two fastest replies, from Northline and Evergreen.
  3. 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 orderSubmission orderCompletion order
Returns whenAll tasks are doneEach take() returns as soon as one more task is done
Best forNeeding every result togetherProcessing 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(); its get() throws ExecutionException.
  • Use poll(timeout, unit) for deadlines. It lets you stop waiting when time runs out instead of blocking.

8. Summary

  • CompletionService returns task results in completion order, not submission order.
  • ExecutorCompletionService wraps any Executor and queues completed futures.
  • take() waits for the next result; poll() returns null if none is ready.
  • It is ideal for processing results early or keeping only the first few.

Related Tutorials

9. References