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:
has one method,Executor . It says nothing about threads; an implementation may run the task on the calling thread.execute(Runnable) addsExecutorService , which accepts asubmit or aRunnable (a task that returns a value and may throw), batch methods, and the lifecycle:Callable ,shutdown ,shutdownNow , and since Java 19awaitTermination , so an executor can sit in try-with-resources.close adds running a task after a delay or repeatedly.ScheduledExecutorService
Most pools are a ThreadPoolExecutorBlockingQueueExecutors
| Method | Since | Threads and queue | Best for |
|---|---|---|---|
newFixedThreadPool(n) | Java 5 | Exactly n threads, unbounded LinkedBlockingQueue | CPU-bound work, n near the number of cores |
newCachedThreadPool() | Java 5 | Unlimited threads, idle ones end after 60 s, SynchronousQueue | Many short tasks in older code |
newSingleThreadExecutor() | Java 5 | One thread, unbounded queue | Tasks that must run one at a time, in order |
newScheduledThreadPool(n) | Java 5 | n threads, delay queue | Timers, heartbeats, retries |
newWorkStealingPool() | Java 8 | A ForkJoinPool | Many small CPU-bound tasks |
newVirtualThreadPerTaskExecutor() | Java 21 | A new virtual thread per task, no pool | Tasks 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.
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:
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]
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.submit blocks until that particular task finishes, and it also guarantees visibility: everything the task did happens-beforeget() 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 aget , shown below.CompletionService ,state() andresultNow() (Java 19) read a completed future without checked exceptions.exceptionNow() throwsresultNow if the task has not succeeded, so call it only after checking the state.IllegalStateException- Only 3 distinct threads ran the 6 tasks. Reusing threads is the point of a pool. The default names
and so on come frompool-1-thread-1 ; pass your ownExecutors.defaultThreadFactory() to get meaningful names.ThreadFactory
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.
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:
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.
catches everything the task throws and stores it in thesubmit . If no one callsFuture , the failure is lost silently. This is the most common reason for "the job just stopped and there is nothing in the log".get has noexecute , so its exception escaped to the thread'sFuture , which printed it. The worker thread died, and the pool created a replacement: the last task ran onUncaughtExceptionHandler .worker-2- With
, the exception arrives wrapped inget() ;ExecutionException gives the originalgetCause() . The future's state isNumberFormatException .FAILED
The rule that follows: for every submitgetexecute
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.
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:
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)
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 oneinvokeAll among twoFAILED .SUCCESS 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 doesinvokeAny throwinvokeAny . This suits querying replicas and taking whichever answers first.ExecutionException wraps an executor and puts each future on a queue when it completes, soExecutorCompletionService 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.take()- Both batch methods have timed versions.
cancels the tasks still running when the time is up.invokeAll(tasks, timeout, unit)
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 getcancelshutdownshutdownNow
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:
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
threwget(200, MILLISECONDS) ; the task kept running untilTimeoutException interrupted it. The task'scancel(true) threwsleep , so it stopped.InterruptedException would only have prevented the task from starting. A task that never checks for interruption cannot be cancelled once it runs.cancel(false) stops new submissions, which then fail withshutdown() , but lets queued tasks finish. Right after the call, the pool was shut down but not terminated;RejectedExecutionException returned true once all 4 queued tasks had run.awaitTermination 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.shutdownNow()
The Javadoc's recommended pattern is shutdown()awaitTerminationshutdownNow()close()
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.
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:
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
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.scheduleAtFixedRate 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.scheduleWithFixedDelay- 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
revealed "disk full". Wrap the body of every repeating task inget() /try and log, or it will stop forever on the first unexpected exception.catch
TimerScheduledExecutorService
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.
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):
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()
Choosing an executor
| Situation | Use |
|---|---|
| CPU-bound tasks | newFixedThreadPool(cores) |
| Tasks that mostly wait on I/O | newVirtualThreadPerTaskExecutor() |
| Need every result | invokeAllsubmitget |
| Need the first good result | invokeAny |
| Handle results as they finish | ExecutorCompletionService |
| Fire and forget | executeUncaughtExceptionHandler |
| Repeating or delayed work | ScheduledExecutorService |
| Chaining asynchronous steps | |
| Recursive divide-and-conquer |
Always shut executors down: try-with-resources since Java 19, or shutdownawaitTermination