CKTIS / Java
util.concurrent.CompletionService: practical reference
util.concurrent.CompletionService: practical reference: CompletionService<V> separates task submission from retrieving Future results in completion order.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.concurrent.CompletionServiceCompletionService separates task submission from retrieving Future results in completion order.
Use it when independent tasks should be handled as soon as each finishes rather than in submission order.
The service normally relies on a separate Executor and does not define its shutdown or lifecycle.
take waits for a completed Future, poll may return null, and submit happens-before the task, which happens-before code after a successful take.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
java.util.concurrent.Executor direct = Runnable::run;
java.util.concurrent.CompletionService<Integer> service = new java.util.concurrent.ExecutorCompletionService<>(direct);
service.submit(() -> 42);
System.out.println(service.take().get());
}
}
Result
42
The example exercises the documented element in a small deterministic program and compares exact standard output.