CKTIS / Java
ExecutorService — tasks, results, and shutdown
ExecutorService separates task submission from execution management. Learn submit, bulk execution with invokeAll, and shutdown, including the distinction between requesting shutdown and waiting for termination.
Version: Java SE 21 (repository runtime); production runtime not attested
Syntax
<T> Future<T> submit(Callable<T> task)
Future<?> submit(Runnable task)
<T> Future<T> submit(Runnable task, T result)
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
void shutdown()java.util.concurrent.ExecutorService extends Executor with result tracking and termination management. This entry targets Java SE 21, the repository runtime. The production runtime is not attested.
ExecutorService.submit returns a Future: for Callable<T> it provides the task result, for Runnable the result is null, and for submit(Runnable, T) it is the supplied value. Future.get() waits if necessary; it reports task failure as ExecutionException, cancellation as CancellationException, and interruption while waiting as InterruptedException.
ExecutorService.invokeAll without a timeout waits for all Callable tasks to finish. Returned futures preserve input order, not completion order. Completion does not imply success: retrieve results and failures through get().
ExecutorService.shutdown rejects new tasks, allows previously accepted tasks to execute, and does not wait. Use awaitTermination to wait; in Java SE 21, close() in try-with-resources shuts down the service and waits. The explicit shutdown() in the example demonstrates the API but is redundant because of close(). Long-running tasks can delay closing.
The example uses Executors.newFixedThreadPool(2). This factory has an unbounded queue: two threads do not limit the number of waiting tasks. Do not treat it as automatic overload protection.
Examples
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Integer> single = pool.submit(() -> 6 * 7);
List<Callable<Integer>> tasks = List.of(() -> 2 + 3, () -> 4 * 5);
List<Future<Integer>> batch = pool.invokeAll(tasks);
pool.shutdown();
System.out.println(single.get());
for (Future<Integer> result : batch) {
System.out.println(result.get());
}
}
}
}Result
42 5 20
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.