ExecutorService Interface in Java: Submit, Manage and Shut Down Tasks
The ExecutorService interface in Java is the type most programs use to run background work. It extends Executor with methods that return results, run batches of tasks, and control the executor's lifecycle.
This tutorial covers its methods, its place in the hierarchy, and two practical examples: picking the fastest working mirror with invokeAny(), and shutting an executor down correctly.
1. What Is ExecutorService?
ExecutorService is an interface in java.util.concurrent, added in Java 5. An implementation owns a set of threads, or creates them on demand, and accepts tasks until it is shut down.
You rarely implement it yourself. You get one from the Executors factory class, or you create a ThreadPoolExecutor or ForkJoinPool directly.
2. ExecutorService Hierarchy
Swipe sideways to see the whole diagram.
Executor(interface): Suppliesexecute(Runnable), which ExecutorService inherits.AutoCloseable(java.lang interface): Since Java 19, ExecutorService extends it, so try-with-resources callsclose()for you.ScheduledExecutorService(interface): A sub-interface that adds delayed and periodic scheduling.AbstractExecutorService(abstract class): A ready-made base that implements the submit and invoke methods.ThreadPoolExecutor and ForkJoinPool(classes): The main implementations shipped with the JDK.
3. Method Details
| Method | Description |
|---|---|
submit(Callable<T>) | Runs a task and returns a Future<T> for its result. |
submit(Runnable) | Returns a Future<?> whose get() returns null on success. |
invokeAll(tasks) | Runs all tasks and returns their futures, in task order, when every one has finished. |
invokeAny(tasks) | Returns the result of one task that completed successfully and cancels the others. |
shutdown() | Stops accepting new tasks; already-submitted tasks still run. Does not wait. |
shutdownNow() | Attempts to stop running tasks and returns the queued tasks that never started. |
awaitTermination(timeout, unit) | Blocks until all tasks finish after a shutdown request, or the timeout expires. |
isShutdown(), isTerminated() | Report whether shutdown was requested and whether everything has finished. |
close() | Java 19+: requests shutdown and waits for all tasks to finish. |
invokeAll() and invokeAny() also have overloads that take a timeout.
4. Example: Downloading from the Fastest Working Mirror
The same file is available from three mirrors. The fastest one is broken, so the program should use the fastest mirror that actually succeeds.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FastestMirrorDownload {
// Simulates downloading the same file from one mirror
static Callable<String> mirror(String host, long latencyMillis, boolean healthy) {
return () -> {
Thread.sleep(latencyMillis);
if (!healthy) {
throw new IllegalStateException(host + " returned HTTP 503");
}
return "jdk-25.tar.gz from " + host + " (" + latencyMillis + " ms)";
};
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Callable<String>> mirrors = List.of(
mirror("eu.mirror.example", 600, true),
mirror("us.mirror.example", 100, false), // fastest, but broken
mirror("ap.mirror.example", 300, true));
try (ExecutorService executor = Executors.newFixedThreadPool(mirrors.size())) {
// invokeAny returns the first SUCCESSFUL result and cancels the rest
String file = executor.invokeAny(mirrors);
System.out.println("Downloaded " + file);
}
}
}
Downloaded jdk-25.tar.gz from ap.mirror.example (300 ms)
How the code works
- Each mirror is a
Callable<String>that sleeps for its latency, then returns the file name or throws. invokeAny()runs all three tasks. The US mirror finishes first but throws, so it does not count.- The Asia-Pacific mirror is the first to complete successfully, so its result is returned, and the slower European download is cancelled.
- If every task had failed,
invokeAny()would throwExecutionException.
5. Example: The Executor Lifecycle
This program fills a single-thread executor with one long report and three queued jobs, then stops it with shutdownNow().
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class ExecutorLifecycleDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
AtomicBoolean interrupted = new AtomicBoolean();
// One long-running report job, then three jobs waiting in the queue
executor.submit(() -> {
started.countDown();
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
interrupted.set(true); // shutdownNow() interrupts running tasks
}
});
for (int i = 1; i <= 3; i++) {
int n = i;
executor.submit(() -> System.out.println("queued job " + n));
}
started.await();
List<Runnable> neverStarted = executor.shutdownNow();
System.out.println("isShutdown: " + executor.isShutdown());
System.out.println("Tasks that never started: " + neverStarted.size());
try {
executor.submit(() -> System.out.println("too late"));
} catch (RejectedExecutionException e) {
System.out.println("New task rejected after shutdown");
}
boolean finished = executor.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("Terminated: " + finished + ", isTerminated: " + executor.isTerminated());
System.out.println("Running report was interrupted: " + interrupted.get());
}
}
isShutdown: true Tasks that never started: 3 New task rejected after shutdown Terminated: true, isTerminated: true Running report was interrupted: true
How the code works
- The
CountDownLatchmakesmainwait until the long report is really running, so the result is the same on every run. shutdownNow()interrupts the running report and returns the three queued jobs, which never print anything.- Any
submit()after a shutdown request throwsRejectedExecutionException. awaitTermination()waits until the interrupted task has returned; after that,isTerminated()istrue.
6. Common Mistakes and Best Practices
- Never shutting down. Pool threads are non-daemon by default and can keep the JVM alive. Use try-with-resources on Java 19+, or
shutdown()in afinallyblock. - Treating
shutdown()as a wait. It returns immediately. Follow it withawaitTermination(), or useclose(). - Tasks that ignore interrupts.
shutdownNow()and cancellation work through interruption; a task that never checks for it may never stop. - Forgetting the Future. Exceptions from
submit()are stored until you callget(). - Choosing the right executor. Use a bounded
ThreadPoolExecutorfor CPU-bound work andExecutors.newVirtualThreadPerTaskExecutor()(Java 21+) for many blocking tasks.
7. Summary
ExecutorServiceextendsExecutorwith result-returningsubmit(), bulkinvokeAll()/invokeAny()and lifecycle control.invokeAny()returns the first successful result and cancels the remaining tasks.shutdown()lets queued work finish;shutdownNow()interrupts running tasks and returns the queued ones.- Since Java 19 it is
AutoCloseable, so try-with-resources shuts it down and waits for you.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between shutdown() and shutdownNow()?
shutdown() stops accepting new tasks but lets submitted tasks run to completion. shutdownNow() also tries to stop running tasks, typically by interrupting them, and returns the list of tasks that were still waiting in the queue.
Q2. What is the difference between invokeAll() and invokeAny()?
invokeAll() waits for every task and returns a list of futures in the same order as the tasks. invokeAny() returns the result of one task that completed successfully and cancels the tasks that have not finished.
Q3. Does shutdown() wait for tasks to finish?
No. It only stops new submissions and returns immediately. Call awaitTermination() to wait, or use close(), which requests shutdown and waits.
Q4. What happens if I submit a task after shutdown()?
The executor rejects it. With the standard implementations, submit() and execute() throw RejectedExecutionException.
Q5. Can ExecutorService be used in try-with-resources?
Yes, since Java 19. ExecutorService extends AutoCloseable, and its close() method shuts the executor down and waits for submitted tasks to finish.