Executor Framework in Java: Run Tasks Without Managing Threads
The Executor Framework in Java is a set of interfaces and classes in the java.util.concurrent package that runs your tasks on managed threads. You hand a task to an executor, and the executor decides which thread runs it and when. It has been part of the JDK since Java 5.
This tutorial covers how the framework is organized, how to collect results and handle failures, and how to shut an executor down. It is current for Java 25 LTS.
1. Why Use the Executor Framework?
Creating a thread for every task has three problems:
- Cost: each platform thread needs its own stack and operating system thread.
- No limit: a burst of requests can start more threads than the machine can handle.
- No results:
Thread.run()returns nothing, so returning a value or an exception needs extra shared state.
The Executor Framework separates what to run (the task) from how it runs (the threading policy). The executor reuses threads, queues extra work and returns results through a Future. Switching policy, for example from a fixed pool to virtual threads, usually means changing one line. For thread basics, see Multithreading in Java.
2. Executor Framework Hierarchy
Swipe sideways to see the whole diagram.
Executor(interface): The root type. Its single method,execute(Runnable), separates submitting a task from deciding which thread runs it and when.AutoCloseable(java.langinterface): Since Java 19,ExecutorServiceextends it, so you can create an executor in a try-with-resources block and haveclose()wait for its tasks.ExecutorService(interface): Addssubmit(),invokeAll()andinvokeAny()for tasks that return results through aFuture, plus lifecycle methods such asshutdown(),awaitTermination()andclose().ScheduledExecutorService(interface): Addsschedule()for one-off delayed tasks, andscheduleAtFixedRate()andscheduleWithFixedDelay()for repeating tasks.AbstractExecutorService(abstract class): Provides ready-madesubmit(),invokeAll()andinvokeAny()built onexecute(), so a concrete executor only has to supplyexecute()and the lifecycle methods. Subclasses can override the protectednewTaskFor()hook.ThreadPoolExecutor(class): The general-purpose, configurable pool: core and maximum pool size, keep-alive time, work queue and rejection handler.newFixedThreadPool()andnewCachedThreadPool()both return one, and you can create it directly when you need a bounded queue.ScheduledThreadPoolExecutor(class): AThreadPoolExecutorthat also runs delayed and periodic tasks, which makes it a more versatile replacement forjava.util.Timer.newScheduledThreadPool()returns one.ForkJoinPool(class): A work-stealing pool in which idle threads take queued work from busy ones. It suits divide-and-conquerForkJoinTaskwork, andnewWorkStealingPool()returns one. Since Java 25, it also implementsScheduledExecutorService.Executors(utility class): A helper class of static factory methods that create and preconfigure the executors above. It does not extend or implement any of them, so it sits outside the hierarchy.
3. Core Building Blocks and Syntax
| Type | Role |
|---|---|
Runnable | A task that returns nothing and cannot throw checked exceptions. |
Callable<V> | A task that returns a value of type V and may throw a checked exception. |
Future<V> | A handle to a pending result: get(), cancel(), isDone(). |
The basic pattern is always the same: create an executor, submit tasks, read the results and shut the executor down.
ExecutorService executor = Executors.newFixedThreadPool(4); // 1. create
Future<String> future = executor.submit(() -> "report ready"); // 2. submit
String result = future.get(); // 3. read the result
executor.shutdown(); // 4. shut down
Use submit(), which returns a Future, rather than execute() whenever you need a result or need to know whether the task failed.
4. Example: Collecting Results with invokeAll()
A purchasing tool asks three suppliers for a steel price and picks the cheapest. Each call is slow, so the program runs them in parallel instead of one after another.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class SupplierQuoteChecker {
record Quote(String supplier, double price) {}
// Simulates a slow call to a supplier's pricing service
static Callable<Quote> fetchQuote(String supplier, double price, long delayMillis) {
return () -> {
Thread.sleep(delayMillis);
return new Quote(supplier, price);
};
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Callable<Quote>> tasks = List.of(
fetchQuote("NorthSteel", 412.50, 300),
fetchQuote("BlueRiver Metals", 398.75, 500),
fetchQuote("Apex Alloys", 405.00, 200));
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
// invokeAll waits for every task and keeps the original order
List<Future<Quote>> futures = executor.invokeAll(tasks);
Quote cheapest = null;
for (Future<Quote> future : futures) {
Quote quote = future.get();
System.out.printf("%-16s %8.2f%n", quote.supplier(), quote.price());
if (cheapest == null || quote.price() < cheapest.price()) {
cheapest = quote;
}
}
System.out.println("Best offer: " + cheapest.supplier());
} finally {
executor.shutdown();
}
}
}
NorthSteel 412.50 BlueRiver Metals 398.75 Apex Alloys 405.00 Best offer: BlueRiver Metals
How the code works
- Each supplier call is a
Callable<Quote>that sleeps to simulate network delay. newFixedThreadPool(3)runs all three calls at once, so the total wait is roughly the slowest call (500 ms), not the sum (1 s).invokeAll()waits for every task and returns the futures in task-list order, so the output is predictable.- Every task is already complete, so
future.get()returns immediately. shutdown()infinallystops the pool even if something throws.
5. Example: Handling a Failed Task
When a task submitted with submit() throws, nothing is printed at that moment. The exception is stored in the Future until someone asks for the result.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class HiddenFailureDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<Integer> future = executor.submit(() -> {
String batchSize = "fifty"; // bad configuration value
return Integer.parseInt(batchSize); // throws NumberFormatException
});
System.out.println("Task submitted, main thread continues...");
try {
Integer size = future.get();
System.out.println("Batch size: " + size);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
System.out.println("Task failed with " + cause.getClass().getSimpleName());
System.out.println("Reason: " + cause.getMessage());
}
} finally {
executor.shutdown();
}
}
}
Task submitted, main thread continues... Task failed with NumberFormatException Reason: For input string: "fifty"
How the code works
- The task throws
NumberFormatExceptionon the worker thread while the main thread keeps running. future.get()rethrows it wrapped inExecutionException;getCause()returns the original exception.- Without the
get()call, the failure would be lost silently. Withexecute(), the exception instead reaches the thread's uncaught exception handler, which prints it to standard error by default.
6. Example: Virtual Threads with try-with-resources
Java 21 added Executors.newVirtualThreadPerTaskExecutor(), which starts a new virtual thread for every task. Virtual threads are cheap, so they suit tasks that mostly wait, such as service health checks. See Java 21 Features.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ServiceHealthCheck {
// Simulated response times in milliseconds; -1 means the service is down
static final Map<String, Integer> SERVICES = Map.of(
"auth-service", 120,
"orders-service", 250,
"inventory-service", -1,
"billing-service", 180);
static String ping(String service) throws InterruptedException {
int latency = SERVICES.get(service);
Thread.sleep(Math.max(latency, 100));
return latency < 0 ? "DOWN" : "UP (" + latency + " ms)";
}
public static void main(String[] args) {
List<String> names = List.of("auth-service", "orders-service", "inventory-service", "billing-service");
List<Future<String>> results = new ArrayList<>();
// Java 21: one virtual thread per task; close() waits for all tasks
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (String name : names) {
results.add(executor.submit(() -> ping(name)));
}
}
for (int i = 0; i < names.size(); i++) {
System.out.printf("%-18s %s%n", names.get(i), results.get(i).resultNow());
}
}
}
auth-service UP (120 ms) orders-service UP (250 ms) inventory-service DOWN billing-service UP (180 ms)
How the code works
- Each
submit()call runsping()on its own virtual thread, so all four checks wait at the same time. - The
try-with-resources block callsclose()(Java 19+), which waits until every submitted task has finished. - After the block,
resultNow()(Java 19+) returns each value without blocking. It throwsIllegalStateExceptionif the task did not complete with a result.
7. Shutting Down an Executor
| Method | What it does |
|---|---|
shutdown() | Stops accepting new tasks; tasks already submitted still run. Does not wait. |
shutdownNow() | Tries to stop running tasks, usually by interrupting them, and returns the tasks that never started. |
awaitTermination(timeout, unit) | Blocks until all tasks finish after a shutdown request, or until the timeout expires. |
close() (Java 19+) | Requests a shutdown and waits for all tasks to finish. |
The default thread factory creates non-daemon threads, so an executor that is never shut down can keep the JVM running. For pool sizing and two-phase shutdown, see Thread Pool in Java.
8. Advantages and Limitations
Advantages
- Reuses threads instead of creating one per task.
- Caps how many tasks run at once.
- Returns results and exceptions through
Future. - Supports bulk execution (
invokeAll(),invokeAny()) and scheduling.
Limitations
Future.get()blocks and offers no callbacks;CompletableFuturefills that gap.- Structured concurrency (
StructuredTaskScope) is still a preview API in Java 25. newFixedThreadPool()uses an unbounded queue, so heavy overload can exhaust memory.
9. Common Mistakes and Best Practices
- Forgetting to shut down. Use try-with-resources (Java 19+) or
shutdown()infinally. - Ignoring the returned
Future. Failures fromsubmit()stay hidden until you callget(). - Waiting forever. Prefer
get(timeout, unit)when a task might hang. - Unbounded queues under load. Create a
ThreadPoolExecutorwith a bounded queue for servers. - Pooling virtual threads. Create one per task; limit scarce resources with a
Semaphore. - Sharing mutable state. Protect shared data with synchronization or thread-safe classes.
10. Summary
- The Executor Framework separates task submission from thread management.
- Use
CallableandFutureto get results and detect failures; exceptions surface throughget()asExecutionException. - On Java 21 and later,
newVirtualThreadPerTaskExecutor()with try-with-resources suits blocking tasks. - Always shut an executor down.
Related Tutorials
11. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between execute() and submit()?
execute(Runnable) comes from Executor and returns nothing, so if the task throws, the exception goes to the worker thread's uncaught exception handler. submit() comes from ExecutorService, accepts a Runnable or a Callable, and returns a Future. Any exception is stored in that Future and rethrown, wrapped in ExecutionException, when you call get().
Q2. What is the difference between shutdown() and shutdownNow()?
shutdown() stops accepting new tasks but lets every task already submitted finish. shutdownNow() also tries to stop running tasks, usually by interrupting their threads, and returns the list of queued tasks that never started. Neither method waits; call awaitTermination() to block until the executor has finished.
Q3. What is the difference between Runnable and Callable?
Runnable.run() returns void and cannot throw checked exceptions. Callable.call() returns a value of type V and is declared to throw Exception. Use Callable when the caller needs a result or must see checked exceptions.
Q4. What does invokeAny() return?
invokeAny() runs a collection of tasks and returns the result of one that completed successfully, meaning without throwing an exception. When it returns, the tasks that have not finished are cancelled. If no task succeeds, it throws ExecutionException.
Q5. Do I still need a thread pool when using virtual threads?
No. Virtual threads are cheap, so Oracle's guidance is to create one per task and never pool them; Executors.newVirtualThreadPerTaskExecutor() does exactly that. If you need to limit how many tasks use a scarce resource, such as database connections, guard that resource with a Semaphore instead of shrinking a pool.