ExecutorService
An ExecutorService is a managed group of worker threads that you hand tasks to. You describe the work, and the service decides which thread runs it and when.
Detailed Explanation
Before executors existed, running work in the background meant writing new Thread(task).start() by hand. That is workable for two or three tasks. It collapses for two hundred. Every platform thread reserves roughly 1 MB of stack address space, creating one is a system call, and two hundred threads competing for eight cores spend much of their life context switching instead of computing. You also had no clean way to get a result back, no way to wait for a whole batch, and no way to say "stop accepting new work".
ExecutorService splits what to run from where it runs. You submit a task. The service owns the threads, the queue in front of them, and the shutdown sequence. Your code stops mentioning threads at all.
You submit work in two shapes. execute(Runnable) is fire and forget. submit accepts a Runnable or a Callable<T>, and hands you back a Future<T> you can wait on, poll, or cancel. invokeAll submits a collection and blocks until every task has finished, which is the shortest correct way to fan out and gather. invokeAny returns as soon as one task succeeds.
The lifecycle has three states and it matters. A new service is running. shutdown() stops it accepting new tasks but lets queued and running ones finish. shutdownNow() drains the queue and interrupts the running threads. Neither one blocks, so you call awaitTermination if you need to know the work is actually done. Since Java 19 ExecutorService is AutoCloseable, so try-with-resources does the whole dance for you: close() calls shutdown() and then waits.
Skipping shutdown is the most common bug here. The threads created by Executors are non-daemon by default, so a forgotten pool keeps the JVM alive after main returns. Your program appears to hang on exit.
What it costs is capacity you have to choose. A pool is a fixed number of threads with a queue in front. Executors.newFixedThreadPool gives you an unbounded queue, so it never refuses work; overload shows up as growing heap and rising latency rather than a clear error. A bounded queue refuses instead, throwing RejectedExecutionException, which is usually the behaviour you want in a service that must stay up.
Reach for an ExecutorService whenever you have many independent units of work: fanning out 200 HTTP calls to a pricing service, resizing uploaded images, processing a Kafka batch. For blocking I/O on Java 21, prefer Executors.newVirtualThreadPerTaskExecutor(), which creates one cheap virtual thread per task instead of queueing behind a small pool.
Code Examples
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PriceFanOut {
// Stands in for a call to a remote pricing service.
static String fetchPrice(String sku) throws InterruptedException {
Thread.sleep(50);
return sku + "=42.00";
}
public static void main(String[] args) throws Exception {
List<String> skus = List.of("sku-1", "sku-2", "sku-3");
// ExecutorService is AutoCloseable since Java 19, so try-with-resources
// shuts the pool down for us even if the body throws.
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
List<Future<String>> pending = new ArrayList<>();
for (String sku : skus) {
// The lambda throws InterruptedException, so it is a Callable<String>,
// not a Runnable, and submit hands back a Future<String>.
pending.add(pool.submit(() -> fetchPrice(sku)));
}
for (Future<String> future : pending) {
System.out.println(future.get()); // blocks until that one task finishes
}
} // close() waits here until every submitted task has completed
}
}import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ManualShutdown {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
pool.execute(() -> System.out.println("work on " + Thread.currentThread().getName()));
} finally {
// The pre-Java-19 shutdown sequence, still worth knowing for interviews.
pool.shutdown(); // refuse new tasks, let current ones finish
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
pool.shutdownNow(); // interrupt whatever is still running
}
}
}
}Common Gotchas
A failing task looks like a silent success
an exception thrown inside a task submitted with `submit` is captured in the `Future`, not printed. You only see it when you call `get()`, wrapped in an `ExecutionException`. Tasks passed to `execute` behave differently and reach the thread's uncaught exception handler.
RejectedExecutionException after shutdown
submitting to a pool that has been shut down, or to a saturated pool with a bounded queue, throws immediately. Treat it as back pressure and decide the policy on purpose rather than letting it surface as a 500.
A forgotten pool keeps the JVM running
`Executors` creates non-daemon threads, so a pool you never shut down prevents the process from exiting. Prefer try-with-resources, or shut down in a `finally` block.
`newFixedThreadPool` never rejects anything
its queue is an unbounded `LinkedBlockingQueue`. Under sustained overload you get an ever-growing queue and eventually `OutOfMemoryError`, long after latency became unacceptable. Build the pool with `ThreadPoolExecutor` and a bounded queue when load is untrusted.