00:00

Executor Framework in Java: Run Tasks Without Managing Threads

Last updated:

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

Executor Framework class hierarchyExecutorService extends the interfaces Executor and java.lang.AutoCloseable. ScheduledExecutorService extends ExecutorService. AbstractExecutorService implements ExecutorService. ThreadPoolExecutor and ForkJoinPool extend AbstractExecutorService. ScheduledThreadPoolExecutor extends ThreadPoolExecutor and implements ScheduledExecutorService. Since Java 25, ForkJoinPool also implements ScheduledExecutorService. Executors is a utility class whose static factory methods create these executors.Java 19+«interface»Executorexecute(Runnable)«interface» · java.langAutoCloseableclose()«interface»ExecutorServicesubmit(Callable) : FutureinvokeAll(tasks) : List<Future>shutdown(), close()«interface»ScheduledExecutorServiceschedule(task, delay, unit)scheduleAtFixedRate(…)«abstract class»AbstractExecutorServicesubmit(), invokeAll(), invokeAny()newTaskFor(…) «protected»«class»ThreadPoolExecutorsetCorePoolSize(int)getActiveCount()«class»ForkJoinPoolcommonPool() «static»invoke(ForkJoinTask)schedule(task, delay, unit) †† added in Java 25«class»ScheduledThreadPoolExecutorschedule(…)scheduleAtFixedRate(…)«utility class»ExecutorsnewFixedThreadPool(int)newScheduledThreadPool(int)newVirtualThreadPerTaskExecutor() †† added in Java 21extendsimplementsinterfaceabstract classclassjava.lang typeutility class

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.lang interface): Since Java 19, ExecutorService extends it, so you can create an executor in a try-with-resources block and have close() wait for its tasks.
  • ExecutorService (interface): Adds submit(), invokeAll() and invokeAny() for tasks that return results through a Future, plus lifecycle methods such as shutdown(), awaitTermination() and close().
  • ScheduledExecutorService (interface): Adds schedule() for one-off delayed tasks, and scheduleAtFixedRate() and scheduleWithFixedDelay() for repeating tasks.
  • AbstractExecutorService (abstract class): Provides ready-made submit(), invokeAll() and invokeAny() built on execute(), so a concrete executor only has to supply execute() and the lifecycle methods. Subclasses can override the protected newTaskFor() hook.
  • ThreadPoolExecutor (class): The general-purpose, configurable pool: core and maximum pool size, keep-alive time, work queue and rejection handler. newFixedThreadPool() and newCachedThreadPool() both return one, and you can create it directly when you need a bounded queue.
  • ScheduledThreadPoolExecutor (class): A ThreadPoolExecutor that also runs delayed and periodic tasks, which makes it a more versatile replacement for java.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-conquer ForkJoinTask work, and newWorkStealingPool() returns one. Since Java 25, it also implements ScheduledExecutorService.
  • 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

TypeRole
RunnableA 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.

BasicUsage.java
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.

SupplierQuoteChecker.java
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();
        }
    }
}
Output
NorthSteel         412.50
BlueRiver Metals   398.75
Apex Alloys        405.00
Best offer: BlueRiver Metals

How the code works

  1. Each supplier call is a Callable<Quote> that sleeps to simulate network delay.
  2. newFixedThreadPool(3) runs all three calls at once, so the total wait is roughly the slowest call (500 ms), not the sum (1 s).
  3. invokeAll() waits for every task and returns the futures in task-list order, so the output is predictable.
  4. Every task is already complete, so future.get() returns immediately.
  5. shutdown() in finally stops 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.

HiddenFailureDemo.java
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();
        }
    }
}
Output
Task submitted, main thread continues...
Task failed with NumberFormatException
Reason: For input string: "fifty"

How the code works

  1. The task throws NumberFormatException on the worker thread while the main thread keeps running.
  2. future.get() rethrows it wrapped in ExecutionException; getCause() returns the original exception.
  3. Without the get() call, the failure would be lost silently. With execute(), 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.

ServiceHealthCheck.java
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());
        }
    }
}
Output
auth-service       UP (120 ms)
orders-service     UP (250 ms)
inventory-service  DOWN
billing-service    UP (180 ms)

How the code works

  1. Each submit() call runs ping() on its own virtual thread, so all four checks wait at the same time.
  2. The try-with-resources block calls close() (Java 19+), which waits until every submitted task has finished.
  3. After the block, resultNow() (Java 19+) returns each value without blocking. It throws IllegalStateException if the task did not complete with a result.

7. Shutting Down an Executor

MethodWhat 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; CompletableFuture fills 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() in finally.
  • Ignoring the returned Future. Failures from submit() stay hidden until you call get().
  • Waiting forever. Prefer get(timeout, unit) when a task might hang.
  • Unbounded queues under load. Create a ThreadPoolExecutor with 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 Callable and Future to get results and detect failures; exceptions surface through get() as ExecutionException.
  • On Java 21 and later, newVirtualThreadPerTaskExecutor() with try-with-resources suits blocking tasks.
  • Always shut an executor down.

Related Tutorials

11. References