Java Executors and Thread Pools: What They Fix and What They Don't
Rewriting a parallel fan-out with ExecutorService and Future: bounded, reused threads and errors that reach the caller. Then the limits that remain: Future.get still blocks, shared queues and cache-line false sharing cost performance, and futures don't compose.
kvi5hnuCode Sprout team member9 min readOn this page
The previous article ran a request's independent calls on hand-made threads and listed what went wrong. The first fix Java offered, back in Java 5, was the Executor framework in java.util.concurrent. Instead of creating threads, you submit tasks to an ExecutorService, and it runs them on threads that it owns and reuses. This article rewrites the trip-quote example with an executor, then looks at the problems an executor doesn't solve.
Submitting tasks and getting Futures
An ExecutorService accepts two kinds of task:
- a
Runnable, which returns nothing, and - a
Callable<V>, whosecall()method returns aVand may throw a checked exception.
submit returns a Future, a handle to the result that doesn't exist yet. future.get() waits until the task finishes, then returns its value. If the task threw an exception, get() throws an ExecutionException whose cause is the original exception. That's the piece raw threads were missing: failures travel back to whoever asks for the result.
With an executor, the fan-out becomes:
static final ExecutorService POOL = Executors.newFixedThreadPool(4);
static Quote quote(long id) throws InterruptedException, ExecutionException {
Traveler traveler = loadTraveler(id);
Future<Flight> flight = POOL.submit(() -> findFlight(traveler));
Future<Hotel> hotel = POOL.submit(() -> findHotel(traveler));
Future<?> search = POOL.submit(() -> recordSearch(id));
Quote quote = price(flight.get(), hotel.get());
search.get();
return quote;
}
There's no AtomicReference and no join(). The Future carries the result and also guarantees visibility: everything the task did happens-before get() returns its value.
Create the pool once
Notice that POOL is a static final field, shared by every request. It's tempting to write try (var pool = Executors.newFixedThreadPool(5)) { ... } inside the request method, and you'll see that in many examples. It works, but it creates and destroys five threads per request, which is the cost the pool was supposed to remove. It also gives each request its own private cap, so 1,000 concurrent requests still create 5,000 threads.
A platform-thread pool is a shared, long-lived resource: create it at startup, size it for the whole application, and close it at shutdown. (Virtual threads change this rule, as Part 2 explains: there, a new executor per request is fine.)
Running it
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Solution {
record Traveler(long id, String homeCity) {}
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
record Quote(int total) {}
static volatile boolean hotelServiceDown = false;
static Traveler loadTraveler(long id) { waitFor(100); return new Traveler(id, "Oslo"); }
static Flight findFlight(Traveler t) { waitFor(100); return new Flight(t.homeCity() + "-Lisbon", 240); }
static Hotel findHotel(Traveler t) {
waitFor(100);
if (hotelServiceDown) throw new IllegalStateException("hotel service unavailable");
return new Hotel("Casa Azul", 360);
}
static void recordSearch(long id) { waitFor(100); }
static Quote price(Flight f, Hotel h) { waitFor(100); return new Quote(f.price() + h.price()); }
// One pool for the whole application, created once and reused by every request
static final ExecutorService POOL = Executors.newFixedThreadPool(4);
static Quote quote(long id) throws InterruptedException, ExecutionException {
Traveler traveler = loadTraveler(id);
Future<Flight> flight = POOL.submit(() -> findFlight(traveler));
Future<Hotel> hotel = POOL.submit(() -> findHotel(traveler));
Future<?> search = POOL.submit(() -> recordSearch(id));
Quote quote = price(flight.get(), hotel.get()); // get() blocks until each result is ready
search.get(); // surface any failure of the side task too
return quote;
}
public static void main(String[] args) throws Exception {
try (POOL) {
for (int request = 1; request <= 2; request++) {
long start = System.nanoTime();
Quote q = quote(request);
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("request " + request + ": total=" + q.total()
+ ", about " + Math.round(ms / 100.0) * 100 + " ms");
}
Future<String> who = POOL.submit(() -> Thread.currentThread().getName());
System.out.println("tasks run on reused threads such as " + who.get().replaceAll("\\d+$", "N"));
hotelServiceDown = true;
try {
quote(3);
} catch (ExecutionException e) {
System.out.println("failure reached the caller: " + e.getCause());
}
}
System.out.println("pool terminated: " + POOL.isTerminated());
}
static void waitFor(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
Output (the rounded times may differ on a busy machine):
request 1: total=600, about 300 ms
request 2: total=600, about 300 ms
tasks run on reused threads such as pool-1-thread-N
failure reached the caller: java.lang.IllegalStateException: hotel service unavailable
pool terminated: true
The latency is the same as with raw threads, about 300 ms, but three things improved:
- Bounded threads. The pool never has more than four threads, however many requests arrive. Extra tasks wait in the pool's queue.
- Reuse. The second request ran on the same threads as the first, so no threads were created for it.
- Errors reach the caller. The hotel failure came back as the cause of an
ExecutionException.
try (POOL) closes the pool at the end of main. Since Java 19, ExecutorService.close() stops accepting new tasks, waits for submitted ones to finish, and then returns. That's why the last line can print true.
What executors don't fix
Future.get() still blocks
get() is a blocking call. The request thread sits in flight.get() for 100 ms, doing nothing, exactly as it sat in join() before. The blocking has moved, not disappeared. A thread-per-request server still needs one blocked thread per in-flight request, plus pool threads blocked on the I/O inside the tasks.
get(timeout, unit) at least bounds the wait, throwing TimeoutException if it runs out. But the timed-out task keeps running unless you also call future.cancel(true), which interrupts it.
Failure doesn't cancel the siblings
When the hotel lookup failed in the run above, the flight lookup and the search log carried on to completion. quote threw as soon as hotel.get() failed, so the search future was simply abandoned, still running, with any failure of its own silently dropped. Cancelling the other futures on failure is up to you, and it's easy to get wrong.
Bounded pools can deadlock
If a task running in a pool submits another task to the same pool and then waits for it, and all pool threads are doing the same, every thread waits for a task that can't start: thread-starvation deadlock. Fan-out inside tasks is natural, so it's a real risk with small fixed pools.
Tasks move data between cores
The tasks in a pool run on whichever thread is free, and that thread may be on a different core from the one that prepared the task's data. Each core has its own small, fast caches (L1, L2, and often a shared L3), which hold memory in fixed-size blocks called cache lines, typically 64 bytes on x86 and 128 bytes on Apple silicon. When data hops between cores, it has to be fetched again into the new core's cache.
Hardware keeps the caches consistent using a cache-coherence protocol such as MESI: when one core writes to a line, copies of that line in other cores' caches are invalidated. That's correct but not free. Two situations are expensive:
- True sharing: threads really do write the same variable, such as a pool's single shared task queue. Every thread taking a task contends for the same lines.
- False sharing: threads write different variables that happen to sit on the same cache line. They never touch each other's data, yet the line bounces between cores on every write.

False sharing is easy to demonstrate. In this program, two threads each increment their own slot of an atomic array. The only difference between the two measurements is the distance between the slots:
import java.util.concurrent.atomic.AtomicLongArray;
public class FalseSharing {
static final int ROUNDS = 50_000_000;
// Two threads each increment their OWN slot; only the distance between the slots changes
static long millis(int distance) throws InterruptedException {
AtomicLongArray slots = new AtomicLongArray(distance + 1);
Thread a = new Thread(() -> { for (int i = 0; i < ROUNDS; i++) slots.getAndIncrement(0); });
Thread b = new Thread(() -> { for (int i = 0; i < ROUNDS; i++) slots.getAndIncrement(distance); });
long start = System.nanoTime();
a.start(); b.start(); a.join(); b.join();
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws InterruptedException {
for (int round = 1; round <= 3; round++) {
System.out.printf("round %d: adjacent slots %4d ms | 256 bytes apart %4d ms%n",
round, millis(1), millis(32));
}
}
}
On one 10-core Apple silicon machine with JDK 25, it printed:
round 1: adjacent slots 519 ms | 256 bytes apart 193 ms
round 2: adjacent slots 492 ms | 256 bytes apart 198 ms
round 3: adjacent slots 494 ms | 256 bytes apart 148 ms
The same work is about 2.5 to 3 times slower when the two counters share a cache line. Your numbers will differ, but the gap is usually large. The JDK avoids this in its own hot classes: LongAdder, ForkJoinPool and parts of ConcurrentHashMap pad frequently written fields with the internal @Contended annotation. In your own code, avoid having different threads write adjacent array elements or neighbouring fields in tight loops: give each thread its own object or accumulate locally and combine at the end.
Futures don't compose
The executor style is imperative: submit, get, submit again, get again. There's no way to say "when the flight and the hotel are both ready, price them, and if either fails, use a fallback" without blocking a thread in get() to wait for each step. Expressing a workflow as a dependency graph, without blocking, needs a different abstraction. Java 8 added one, CompletableFuture, the subject of the next article.
What's current
ExecutorServiceimplementsAutoCloseablesince Java 19. Use try-with-resources for executors whose lifetime is a block, and an explicitclose()(orshutdown()plusawaitTermination) at application shutdown for long-lived ones.Future.state(),resultNow()andexceptionNow()(Java 19) let you inspect a completed future without catchingExecutionException.Executors.newVirtualThreadPerTaskExecutor()(Java 21) runs each task on a new virtual thread. With it, blocking inget()is cheap, which changes most of the trade-offs in this article. Part 2 explains why.
Common questions
What happens to tasks submitted when all four pool threads are busy?
They wait in the pool's queue. newFixedThreadPool uses an unbounded LinkedBlockingQueue, so submission never fails, but a backlog can grow without limit and use a lot of memory. Article 20 shows how to build a ThreadPoolExecutor with a bounded queue and a rejection policy.
Is submit different from execute?
execute(Runnable), from the base Executor interface, returns nothing, and an exception thrown by the task goes to the thread's uncaught exception handler. submit wraps the task in a Future, which captures the exception. Never call submit and then ignore the future: if the task fails, nobody will ever know.
How do I pick a pool size?
For CPU-bound work, about the number of cores (Runtime.getRuntime().availableProcessors()). For blocking work, more, roughly cores × (1 + wait time / compute time), limited by memory and by what downstream systems can take. Article 10 derives this from Little's Law, and virtual threads make the question mostly go away for blocking work.
Is false sharing something I need to worry about in business code? Rarely. It matters in tight loops where several threads write to memory locations within a few dozen bytes of each other, millions of times per second: counters, statistics, queue indices. Ordinary request handling doesn't come close. But it's worth recognizing when a "parallel" version is mysteriously slower than the sequential one.
Summary
- An
ExecutorServiceruns submitted tasks on threads it owns and reuses.submitreturns aFuture. Future.get()returns the result or throwsExecutionExceptionwith the original exception as its cause, so failures reach the caller.- Create a platform-thread pool once per application, not once per request.
get()still blocks the calling thread, failures don't cancel sibling tasks, and small bounded pools can deadlock when tasks wait for other tasks.- Work moving between cores pays for cache misses and coherence traffic. False sharing, when threads write different variables on the same cache line, can make code several times slower.
- Futures don't compose without blocking, which motivated
CompletableFuture.
Practice questions
What does this code print, and why?
try (var pool = Executors.newFixedThreadPool(2)) {
Future<Integer> f = pool.submit(() -> Integer.parseInt("forty-two"));
try {
System.out.println(f.get());
} catch (ExecutionException e) {
System.out.println(e.getCause().getClass().getSimpleName());
}
}
Answer
It prints NumberFormatException. The task's exception is caught by the future and rethrown by get(), wrapped in an ExecutionException. The original exception is its cause.
A fixed pool has two threads. Each of two running tasks submits a subtask to the same pool and calls get() on it. What happens?
Answer
Thread-starvation deadlock. Both pool threads are blocked in get(), waiting for subtasks that sit in the queue and can never start, because there's no free thread to run them. Use a separate pool for subtasks, a larger pool, a timeout, or a design where tasks don't wait for other tasks in the same pool.
Eight threads each increment counts[threadIndex] in a shared long[] counts = new long[8] a billion times. Why might this be slower than expected, and what's a simple fix?
Answer
All eight longs fit in 64 bytes, so they share one or two cache lines, and every increment invalidates the line in the other cores' caches (false sharing). Give each thread a local variable to count in and write the total to the array once at the end, or space the slots at least one cache line apart.
Previous: Blocking I/O and Parallel Fan-Out in Java: Speeding Up a Request With Raw Threads
Next: Java ForkJoinPool and CompletableFuture: Work Stealing and Composable Async Code

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.