00:00

ExecutorService Interface in Java: Submit, Manage and Shut Down Tasks

Last updated:

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

ExecutorService interface hierarchyExecutorService extends Executor and java.lang.AutoCloseable. ScheduledExecutorService extends ExecutorService. AbstractExecutorService implements ExecutorService; ThreadPoolExecutor and ForkJoinPool extend AbstractExecutorService.«interface»Executorexecute(Runnable)«interface» · java.langAutoCloseableclose()«interface»ExecutorServicethis pagesubmit(…) : FutureinvokeAll(…), invokeAny(…)shutdown(), shutdownNow()awaitTermination(…)close() †† added in Java 19«interface»ScheduledExecutorServiceschedule(…)«abstract class»AbstractExecutorServicesubmit(), invokeAll()«class»ThreadPoolExecutor«class»ForkJoinPoolextendsimplementsinterfaceabstract classclassjava.lang type

Swipe sideways to see the whole diagram.

  • Executor (interface): Supplies execute(Runnable), which ExecutorService inherits.
  • AutoCloseable (java.lang interface): Since Java 19, ExecutorService extends it, so try-with-resources calls close() 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

MethodDescription
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.

FastestMirrorDownload.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;

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);
        }
    }
}
Output
Downloaded jdk-25.tar.gz from ap.mirror.example (300 ms)

How the code works

  1. Each mirror is a Callable<String> that sleeps for its latency, then returns the file name or throws.
  2. invokeAny() runs all three tasks. The US mirror finishes first but throws, so it does not count.
  3. The Asia-Pacific mirror is the first to complete successfully, so its result is returned, and the slower European download is cancelled.
  4. If every task had failed, invokeAny() would throw ExecutionException.

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().

ExecutorLifecycleDemo.java
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());
    }
}
Output
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

  1. The CountDownLatch makes main wait until the long report is really running, so the result is the same on every run.
  2. shutdownNow() interrupts the running report and returns the three queued jobs, which never print anything.
  3. Any submit() after a shutdown request throws RejectedExecutionException.
  4. awaitTermination() waits until the interrupted task has returned; after that, isTerminated() is true.

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 a finally block.
  • Treating shutdown() as a wait. It returns immediately. Follow it with awaitTermination(), or use close().
  • 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 call get().
  • Choosing the right executor. Use a bounded ThreadPoolExecutor for CPU-bound work and Executors.newVirtualThreadPerTaskExecutor() (Java 21+) for many blocking tasks.

7. Summary

  • ExecutorService extends Executor with result-returning submit(), bulk invokeAll() / 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