ExecutorService

An ExecutorService runs tasks on threads it manages, so you submit work instead of creating threads. Each submission returns a Future that later delivers the result or the exception. This page explains the executor interfaces and factory methods, then runs futures, the exceptions that silently disappear, batch methods, cancellation and shutdown, scheduling, and a comparison of pools with virtual threads.

Contents

What an executor does

Creating a thread per task works for a few tasks, but it gives you no limit on how many threads exist, no way to get a result back, and no single place to stop everything. The executor framework, added in Java 5 by JSR 166, separates what to run from how it runs. You hand a task to an executor and get back a Future, a handle for a result that does not exist yet.

Three interfaces build on each other:

  • Executor has one method, execute(Runnable). It says nothing about threads; an implementation may run the task on the calling thread.
  • ExecutorService adds submit, which accepts a Runnable or a Callable (a task that returns a value and may throw), batch methods, and the lifecycle: shutdown, shutdownNow, awaitTermination, and since Java 19 close, so an executor can sit in try-with-resources.
  • ScheduledExecutorService adds running a task after a delay or repeatedly.

Most pools are a ThreadPoolExecutor: a set of worker threads that loop, taking tasks from a BlockingQueue. The Executors factory methods configure it in a few standard ways. How the queue and the pool size interact is covered on the ThreadPoolExecutor page.

The Executors factory methods
MethodSinceThreads and queueBest for
newFixedThreadPool(n)Java 5Exactly n threads, unbounded LinkedBlockingQueueCPU-bound work, n near the number of cores
newCachedThreadPool()Java 5Unlimited threads, idle ones end after 60 s, SynchronousQueueMany short tasks in older code
newSingleThreadExecutor()Java 5One thread, unbounded queueTasks that must run one at a time, in order
newScheduledThreadPool(n)Java 5n threads, delay queueTimers, heartbeats, retries
newWorkStealingPool()Java 8A ForkJoinPool with one queue per threadMany small CPU-bound tasks
newVirtualThreadPerTaskExecutor()Java 21A new virtual thread per task, no poolTasks that mostly wait on I/O

Every program on this page was compiled and run with JDK 21. Thread names and finishing order vary between runs, so the programs print checks and rounded times instead.

Submitting tasks and reading Futures

Six tasks of 200 ms run on a pool of 3 threads. Each returns the square of its number, so the combined result, 1 + 4 + ... + 36 = 91, shows that every result arrived.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class PoolsAndFutures {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Set<String> threadNames = ConcurrentHashMap.newKeySet();
        long start = System.nanoTime();

        try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
            // submit(Callable) returns at once with a Future for the result
            List<Future<Integer>> futures = new ArrayList<>();
            for (int job = 1; job <= 6; job++) {
                int n = job;
                Callable<Integer> task = () -> {
                    threadNames.add(Thread.currentThread().getName());
                    Thread.sleep(200);                 // pretend to work
                    return n * n;
                };
                futures.add(pool.submit(task));
            }
            System.out.println("submitted 6 tasks after " + elapsed(start) + " ms");
            System.out.println("first future done yet? " + futures.get(0).isDone());

            int sum = 0;
            for (Future<Integer> f : futures) {
                sum += f.get();                        // blocks until that task is done
            }
            System.out.println("sum of squares 1..6 = " + sum);
            System.out.println("all results after about " + elapsed(start) + " ms");
            System.out.println("first future state: " + futures.get(0).state()
                    + ", resultNow = " + futures.get(0).resultNow());
        }                                              // close(): shutdown and wait
        System.out.println("distinct threads used: " + threadNames.size() + " "
                + new TreeSet<>(threadNames));
    }

    static long elapsed(long start) {
        return (System.nanoTime() - start) / 100000000 * 100;   // rounded down to 100 ms
    }
}

Output:

Output
submitted 6 tasks after 0 ms
first future done yet? false
sum of squares 1..6 = 91
all results after about 400 ms
first future state: SUCCESS, resultNow = 1
distinct threads used: 3 [pool-1-thread-1, pool-1-thread-2, pool-1-thread-3]
  • submit returned at once: all 6 tasks were queued after 0 ms, and the first future was not done yet. The tasks then ran in two waves of 3, so all results were ready after about 400 ms, not the 1,200 ms of running them one after another.
  • get() blocks until that particular task finishes, and it also guarantees visibility: everything the task did happens-before get returns. Reading the futures in submission order is fine when you need all of them; to handle each as soon as it is ready, use a CompletionService, shown below.
  • state(), resultNow() and exceptionNow() (Java 19) read a completed future without checked exceptions. resultNow throws IllegalStateException if the task has not succeeded, so call it only after checking the state.
  • Only 3 distinct threads ran the 6 tasks. Reusing threads is the point of a pool. The default names pool-1-thread-1 and so on come from Executors.defaultThreadFactory(); pass your own ThreadFactory to get meaningful names.

Exceptions that disappear

A task's exception goes to different places depending on how the task was handed over. The program uses a single-thread pool with a named thread factory and a handler that prints anything it receives, then fails three tasks in three ways.

Java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

public class LostExceptions {

    public static void main(String[] args) throws InterruptedException {
        ThreadFactory named = Thread.ofPlatform().name("worker-", 1)
                .uncaughtExceptionHandler((t, e) ->
                        System.out.println("handler saw " + e + " on " + t.getName()))
                .factory();

        try (ExecutorService pool = Executors.newSingleThreadExecutor(named)) {
            // 1. submit(): the exception is stored in the Future; nobody looks, nothing printed
            pool.submit(() -> {
                throw new IllegalStateException("from submit, ignored Future");
            });

            // 2. execute(): no Future, so the exception reaches the thread's handler
            pool.execute(() -> {
                throw new IllegalStateException("from execute");
            });
            Thread.sleep(200);

            // 3. submit() and get(): the exception arrives wrapped in ExecutionException
            Future<Integer> parse = pool.submit(() -> Integer.parseInt("12x"));
            try {
                parse.get();
            } catch (ExecutionException e) {
                System.out.println("get() threw ExecutionException, cause: " + e.getCause());
            }
            System.out.println("state " + parse.state() + ", exceptionNow: "
                    + parse.exceptionNow().getClass().getSimpleName());

            // 4. The pool replaced the thread that died in execute()
            Future<String> who = pool.submit(() -> Thread.currentThread().getName());
            try {
                System.out.println("next task runs on " + who.get());
            } catch (ExecutionException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

Output:

Output
handler saw java.lang.IllegalStateException: from execute on worker-1
get() threw ExecutionException, cause: java.lang.NumberFormatException: For input string: "12x"
state FAILED, exceptionNow: NumberFormatException
next task runs on worker-2
  • The first task's exception, "from submit, ignored Future", appears nowhere in the output. submit catches everything the task throws and stores it in the Future. If no one calls get, the failure is lost silently. This is the most common reason for "the job just stopped and there is nothing in the log".
  • execute has no Future, so its exception escaped to the thread's UncaughtExceptionHandler, which printed it. The worker thread died, and the pool created a replacement: the last task ran on worker-2.
  • With get(), the exception arrives wrapped in ExecutionException; getCause() gives the original NumberFormatException. The future's state is FAILED.

The rule that follows: for every submit, something must eventually call get or check the state, or the task must catch and log its own exceptions. For fire-and-forget work, execute with a logging handler is the safer choice.

Batches: invokeAll, invokeAny and CompletionService

Three servers answer a lookup after 100, 200 and 300 ms, and the fastest one, "us", fails. The delays are far enough apart that the order of events is the same on every run.

Java
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class InvokeAllAny {

    static Callable<String> lookup(String server, long ms, boolean fails) {
        return () -> {
            Thread.sleep(ms);
            if (fails) {
                throw new IllegalStateException(server + " is down");
            }
            return server + " (" + ms + " ms)";
        };
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Callable<String>> tasks = List.of(
                lookup("eu", 300, false), lookup("us", 100, true), lookup("asia", 200, false));

        try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
            // invokeAll: run all, wait for all, futures come back in task order
            long t0 = System.nanoTime();
            for (Future<String> f : pool.invokeAll(tasks)) {
                System.out.println("invokeAll: " + f.state() + " "
                        + (f.state() == Future.State.SUCCESS ? f.resultNow()
                                : f.exceptionNow().getMessage()));
            }
            System.out.println("invokeAll returned after about " + ms(t0) + " ms");

            // invokeAny: first SUCCESSFUL result; failures are skipped, the rest cancelled
            t0 = System.nanoTime();
            System.out.println("invokeAny: " + pool.invokeAny(tasks)
                    + " after about " + ms(t0) + " ms");

            // CompletionService: results in the order they finish
            CompletionService<String> cs = new ExecutorCompletionService<>(pool);
            for (Callable<String> t : tasks) {
                cs.submit(t);
            }
            for (int i = 0; i < tasks.size(); i++) {
                Future<String> done = cs.take();       // the next one to finish
                System.out.println("completed #" + (i + 1) + ": " + (done.state()
                        == Future.State.SUCCESS ? done.resultNow() : "failed"));
            }
        }
    }

    static long ms(long t0) {
        return (System.nanoTime() - t0) / 100000000 * 100;
    }
}

Output:

Output
invokeAll: SUCCESS eu (300 ms)
invokeAll: FAILED us is down
invokeAll: SUCCESS asia (200 ms)
invokeAll returned after about 300 ms
invokeAny: asia (200 ms) after about 200 ms
completed #1: failed
completed #2: asia (200 ms)
completed #3: eu (300 ms)
  • invokeAll returned after about 300 ms, when the slowest task finished, with the futures in the order of the task list: eu, us, asia. It does not throw for failed tasks; each future records its own outcome, here one FAILED among two SUCCESS.
  • invokeAny returned the first successful result. "us" finished first but failed, so it was skipped, and "asia" won after about 200 ms. The remaining task was cancelled. Only if every task fails does invokeAny throw ExecutionException. This suits querying replicas and taking whichever answers first.
  • ExecutorCompletionService wraps an executor and puts each future on a queue when it completes, so take() returns them in finishing order: the failed one at 100 ms, then asia, then eu. Use it to process results as they arrive instead of waiting for the slowest.
  • Both batch methods have timed versions. invokeAll(tasks, timeout, unit) cancels the tasks still running when the time is up.

Cancellation and shutdown

An executor's threads are not daemon threads, so a program that never shuts its executor down never exits. The program shows a timed get followed by cancel, then the difference between shutdown and shutdownNow.

Java
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CancelAndShutdown {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        // 1. get with a timeout, then cancel(true), which interrupts the running task
        Future<String> slow = pool.submit(() -> {
            try {
                Thread.sleep(5000);
                return "finished";
            } catch (InterruptedException e) {
                System.out.println("1. task saw the interrupt and stopped");
                throw e;
            }
        });
        try {
            slow.get(200, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            System.out.println("1. get timed out; cancel(true) = " + slow.cancel(true)
                    + ", state " + slow.state());
        }
        Thread.sleep(50);

        // 2. shutdown(): no new tasks, but queued ones still run
        for (int i = 1; i <= 4; i++) {
            int id = i;
            pool.submit(() -> {
                Thread.sleep(100);
                return id;
            });
        }
        pool.shutdown();
        System.out.println("2. isShutdown " + pool.isShutdown() + ", isTerminated "
                + pool.isTerminated());
        try {
            pool.submit(() -> "late");
        } catch (RejectedExecutionException e) {
            System.out.println("2. submit after shutdown: RejectedExecutionException");
        }
        System.out.println("2. awaitTermination: " + pool.awaitTermination(2, TimeUnit.SECONDS)
                + " (all 4 queued tasks ran)");

        // 3. shutdownNow(): interrupts running tasks and returns the ones never started
        ExecutorService pool2 = Executors.newFixedThreadPool(2);
        for (int i = 1; i <= 6; i++) {
            pool2.submit(() -> {
                Thread.sleep(10000);
                return null;
            });
        }
        Thread.sleep(100);
        List<Runnable> neverStarted = pool2.shutdownNow();
        System.out.println("3. shutdownNow returned " + neverStarted.size()
                + " tasks that never started");
        System.out.println("3. terminated within 1 s: "
                + pool2.awaitTermination(1, TimeUnit.SECONDS));
    }
}

Output:

Output
1. task saw the interrupt and stopped
1. get timed out; cancel(true) = true, state CANCELLED
2. isShutdown true, isTerminated false
2. submit after shutdown: RejectedExecutionException
2. awaitTermination: true (all 4 queued tasks ran)
3. shutdownNow returned 4 tasks that never started
3. terminated within 1 s: true
  1. get(200, MILLISECONDS) threw TimeoutException; the task kept running until cancel(true) interrupted it. The task's sleep threw InterruptedException, so it stopped. cancel(false) would only have prevented the task from starting. A task that never checks for interruption cannot be cancelled once it runs.
  2. shutdown() stops new submissions, which then fail with RejectedExecutionException, but lets queued tasks finish. Right after the call, the pool was shut down but not terminated; awaitTermination returned true once all 4 queued tasks had run.
  3. shutdownNow() interrupts running tasks and removes queued ones from the queue, returning them: 2 tasks were running on the 2 threads, so the other 4 never started. The pool terminated within a second because the running tasks responded to the interrupt.

The Javadoc's recommended pattern is shutdown(), then awaitTermination with a timeout, then shutdownNow() if tasks are still running. Since Java 19, close() does the first two steps, waiting without a time limit, which is what the try-with-resources blocks on this page rely on.

Scheduling: fixed rate versus fixed delay

A scheduled executor can repeat a task in two ways that differ when the task itself takes time. Both tasks here take 120 ms and are scheduled every 200 ms; start times are rounded to 40 ms. The program then shows what happens when a repeating task throws.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Scheduled {

    public static void main(String[] args) throws InterruptedException {
        try (ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2)) {
            // Both tasks take 120 ms; the period or delay is 200 ms
            List<Long> rateStarts = new ArrayList<>();
            List<Long> delayStarts = new ArrayList<>();
            long t0 = System.nanoTime();
            ScheduledFuture<?> rate = scheduler.scheduleAtFixedRate(
                    () -> work(rateStarts, t0), 0, 200, TimeUnit.MILLISECONDS);
            ScheduledFuture<?> delay = scheduler.scheduleWithFixedDelay(
                    () -> work(delayStarts, t0), 0, 200, TimeUnit.MILLISECONDS);
            Thread.sleep(1100);
            rate.cancel(false);
            delay.cancel(false);
            Thread.sleep(150);
            synchronized (rateStarts) {
                System.out.println("fixed rate starts (ms):  " + rateStarts);
            }
            synchronized (delayStarts) {
                System.out.println("fixed delay starts (ms): " + delayStarts);
            }

            // The trap: one exception silently cancels all future runs
            AtomicInteger runs = new AtomicInteger();
            ScheduledFuture<?> fragile = scheduler.scheduleAtFixedRate(() -> {
                if (runs.incrementAndGet() == 3) {
                    throw new IllegalStateException("disk full");
                }
            }, 0, 50, TimeUnit.MILLISECONDS);
            Thread.sleep(500);
            System.out.println("fragile task ran " + runs.get() + " times in 500 ms, isDone "
                    + fragile.isDone());
            try {
                fragile.get();
            } catch (ExecutionException e) {
                System.out.println("its Future holds the reason: " + e.getCause().getMessage());
            }
        }
    }

    static void work(List<Long> starts, long t0) {
        long ms = (System.nanoTime() - t0) / 1000000;
        synchronized (starts) {
            starts.add(Math.round(ms / 40.0) * 40);       // rounded to 40 ms
        }
        try {
            Thread.sleep(120);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
fixed rate starts (ms):  [0, 200, 400, 600, 800, 1000]
fixed delay starts (ms): [0, 320, 640, 960]
fragile task ran 3 times in 500 ms, isDone true
its Future holds the reason: disk full
  • scheduleAtFixedRate starts runs at 0, 200, 400 ms and so on, measured from the first start, however long each run takes. If one run takes longer than the period, the next starts late but runs never overlap.
  • scheduleWithFixedDelay waits 200 ms after each run ends, so its starts are 120 + 200 = 320 ms apart: 0, 320, 640, 960. Use it when runs must have a gap, for example polling a server that should get a rest.
  • The trap: the third run of the fragile task threw, and the task was never run again, with no message anywhere. Its future became done, and only get() revealed "disk full". Wrap the body of every repeating task in try/catch and log, or it will stop forever on the first unexpected exception.

Timer (Java 1.3) does the same job worse: a single thread, and one exception kills the whole timer with all its tasks. Prefer ScheduledExecutorService.

Pools versus virtual threads for waiting tasks

Ten thousand tasks that each wait 50 ms, standing in for remote calls, run on three executors. The ideal time for all of them running at once is 50 ms. Each executor runs 3 times and the best time is reported; this is a rough comparison, not a benchmark.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

public class VirtualVsPool {

    public static void main(String[] args) {
        int tasks = 10000;
        System.out.printf("%,d tasks that each wait 50 ms, best of 3%n", tasks);
        time("newFixedThreadPool(100)", tasks, () -> Executors.newFixedThreadPool(100));
        time("newCachedThreadPool()", tasks, Executors::newCachedThreadPool);
        time("newVirtualThreadPerTaskExecutor", tasks,
                Executors::newVirtualThreadPerTaskExecutor);
    }

    static void time(String name, int tasks, Supplier<ExecutorService> factory) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            try (ExecutorService exec = factory.get()) {
                for (int i = 0; i < tasks; i++) {
                    exec.submit(() -> {
                        Thread.sleep(50);              // stands in for a remote call
                        return null;
                    });
                }
            }                                          // close() waits for all tasks
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-34s %,6d ms%n", name, best / 1000000);
    }
}

Output (one run on a 2-CPU Linux machine with JDK 21):

Output
10,000 tasks that each wait 50 ms, best of 3
newFixedThreadPool(100)             5,024 ms
newCachedThreadPool()                 619 ms
newVirtualThreadPerTaskExecutor        83 ms
  • The fixed pool of 100 threads took about 5 seconds: 10,000 tasks in waves of 100, each wave 50 ms. The pool size, not the CPU, was the limit, because the threads spent their time waiting.
  • The cached pool was roughly eight to ten times faster, because it created a new platform thread whenever none was idle, close to one per task. That speed comes from creating thousands of OS threads, which on a busy server can exhaust memory or the process limit.
  • The virtual thread executor was the fastest, within a few tens of milliseconds of the ideal. It creates a cheap virtual thread per task and does not pool them. To limit how many tasks hit a remote service at once, use a Semaphore rather than a smaller pool.

For CPU-bound tasks the picture reverses: more threads than cores only add switching, and a fixed pool sized to Runtime.getRuntime().availableProcessors() is the right choice.

Choosing an executor

Which executor and which method
SituationUse
CPU-bound tasksnewFixedThreadPool(cores), or a ThreadPoolExecutor with a bounded queue
Tasks that mostly wait on I/OnewVirtualThreadPerTaskExecutor()
Need every resultinvokeAll, or submit and get each future
Need the first good resultinvokeAny
Handle results as they finishExecutorCompletionService
Fire and forgetexecute with an UncaughtExceptionHandler that logs
Repeating or delayed workScheduledExecutorService, with try/catch inside the task
Chaining asynchronous stepsCompletableFuture
Recursive divide-and-conquerForkJoinPool

Always shut executors down: try-with-resources since Java 19, or shutdown and awaitTermination in older code. For the threads underneath, see thread basics and virtual threads.