ExecutorService in Java: Thread Pool, Callable and Future
ExecutorService is an interface in java.util.concurrent that manages a pool of threads and a queue of tasks. Instead of creating a Thread by hand, you hand a task to the pool with submit() or execute(), a free pool thread runs it, and you get the result through a Future object. When the work is done, you close the pool with shutdown() or, since Java 19, with try-with-resources: ExecutorService extends AutoCloseable, and its close() waits for every submitted task to finish.
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
Future<Integer> future = pool.submit(() -> 2 + 2); // the task goes to the pool
System.out.println(future.get()); // Output: 4
} // close(): wait for tasks and stop the pool Forget to close the pool, and the program may never end. Create Executors.newFixedThreadPool(2), submit one task that prints “Done”, and let main return: the line gets printed, and the process keeps hanging without a single error, because the pool threads aren't daemons and sit waiting for new tasks. Why this happens and how to fix it is covered in Shutting Down a Pool.
Why Use a Thread Pool
A Java thread pool exists so you don’t create a new thread for every task. A platform thread is an operating-system thread with its own stack; creating and destroying one is expensive, and an unbounded number of threads leads to OutOfMemoryError and to a CPU busy with context switches instead of work. A pool keeps a few threads alive and hands them tasks from a queue.
Here is the “manual” version: five tasks, five new threads, each living for exactly one task.
for (int i = 1; i <= 5; i++) {
int taskId = i;
new Thread(() -> System.out.println("Task " + taskId + " on " + Thread.currentThread().getName())).start();
}
// Threads Thread-0 … Thread-4: five creations and five teardowns Five threads are no problem. But handle every HTTP request this way, and a traffic spike makes the program create ten thousand threads, each reserving memory for its stack. The same work through a pool of two threads:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolReuse {
public static void main(String[] args) {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
for (int i = 1; i <= 5; i++) {
int taskId = i;
pool.execute(() -> System.out.println(
"Task " + taskId + " on " + Thread.currentThread().getName()));
}
} // close() waits until all five tasks have run
System.out.println("All tasks done");
}
} One possible output:
Task 1 on pool-1-thread-1
Task 2 on pool-1-thread-2
Task 3 on pool-1-thread-1
Task 5 on pool-1-thread-1
Task 4 on pool-1-thread-2
All tasks done The task order, and which thread picks up which task, changes from run to run. What is guaranteed: only two threads do the work, named pool-N-thread-M, and “All tasks done” is always the last line, because close() at the end of the try block waits for the tasks. The task is decoupled from the thread — the same idea that makes Runnable preferable to extending Thread (see Thread vs Runnable).
Besides saving resources, a pool gives you control: the number of tasks running at once is capped by the pool size, the rest wait in the queue, and a single call stops all the work.
The Executors Factory: Which Pool to Choose
Ready-made pools come from static methods of the Executors class: newFixedThreadPool(n) — a fixed number of threads, newCachedThreadPool() — threads on demand, newSingleThreadExecutor() — one thread, newScheduledThreadPool(n) — scheduled tasks, newVirtualThreadPerTaskExecutor() — a virtual thread per task (Java 21). Each one has a catch that only shows once you look at how it’s built.
| Method | What’s inside | When to use it | Risk |
|---|---|---|---|
newFixedThreadPool(n) | ThreadPoolExecutor: exactly n threads, an unbounded LinkedBlockingQueue | Predictable load, computations, the “default” pool | The queue is unbounded: if tasks arrive faster than they complete, it grows until OutOfMemoryError |
newCachedThreadPool() | From 0 to Integer.MAX_VALUE threads, a SynchronousQueue (stores no tasks), an idle thread lives 60 s | Many short tasks under moderate load | No free thread means a new one is created; under a load spike you get thousands of threads |
newSingleThreadExecutor() | One thread, an unbounded queue; if the thread dies, a new one replaces it | Tasks must run strictly one after another, in submission order | The same unbounded queue; one long task delays all the others |
newScheduledThreadPool(n) | ScheduledThreadPoolExecutor with n threads and a queue ordered by start time | Delays and periodic tasks (section below) | An exception in a periodic task silently cancels all its future runs |
newVirtualThreadPerTaskExecutor() | A new virtual thread for each task, no queue and no limit (Java 21) | Thousands of tasks that mostly wait for the network or disk | No limit: every database query goes out at once; doesn’t speed up computations |
newWorkStealingPool() | ForkJoinPool with parallelism equal to the number of cores (Java 8); idle threads “steal” tasks from busy ones | Many small independent computational tasks | Threads are daemons: if main doesn’t wait for the result, the JVM exits before the tasks finish; execution order isn’t FIFO |
The queue problem in Executors.newFixedThreadPool() is especially nasty: everything works in tests, while in production the queue slowly grows for hours. That’s why server code often builds the pool by hand through ThreadPoolExecutor with a bounded queue — see its own section.
All methods except newWorkStealingPool and newVirtualThreadPerTaskExecutor create threads through the default factory: ordinary threads with NORM_PRIORITY, not daemons, named pool-N-thread-M. Each method has an overload that takes a ThreadFactory if you need different names or settings (example in the FAQ).
execute() vs submit(): Where the Exception Goes
execute(Runnable) returns nothing, and an exception from the task is thrown in the pool thread: the UncaughtExceptionHandler handles it and, by default, prints the stack trace. submit() returns a Future and hides the exception inside it — you see it only by calling future.get(), which throws ExecutionException.
| Method | Returns | Exception from the task |
|---|---|---|
void execute(Runnable) (from the Executor interface) | Nothing | Kills the pool thread, the UncaughtExceptionHandler prints the stack trace; the pool creates a replacement thread |
Future<?> submit(Runnable) | A Future whose get() returns null | Stored in the Future; get() throws ExecutionException, the original exception is in getCause(). Without get(), nobody ever sees it |
Future<T> submit(Runnable, T result) | A Future whose get() returns result | |
Future<T> submit(Callable<T>) | A Future with the result of call() |
What does this code print?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecuteVsSubmit {
public static void main(String[] args) {
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
pool.execute(() -> {
throw new IllegalStateException("error from execute");
});
pool.submit(() -> {
throw new IllegalStateException("error from submit");
});
}
System.out.println("main finished");
}
} Exception in thread "pool-1-thread-1" java.lang.IllegalStateException: error from execute
at ExecuteVsSubmit.lambda$main$0(ExecuteVsSubmit.java:8)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:...)
...
main finished The second error isn’t in the output at all. The task passed to submit() failed in exactly the same way, but the exception sits in a Future nobody read. In code review this is one of the most frequent finds in concurrent code: pool.submit(task) with the Future thrown away, and a task that “sometimes doesn’t run” for months without a trace in the logs. The rule is simple: if you don’t need the result, use execute(); if you use submit(), call get() or catch exceptions inside the task itself.
Two details from the output. The stack trace goes to System.err, so in an IDE console it may appear after “main finished”. And pool-1-thread-1 died after the exception — the second task was run by a new thread, pool-1-thread-2, which the pool created as a replacement.
Callable vs Runnable: What’s the Difference
Callable<V> is a functional interface from java.util.concurrent (Java 5) with the method V call() throws Exception. Unlike Runnable with its void run(), it returns a result and may throw checked exceptions. You can’t pass a Callable to a Thread constructor — it goes to an ExecutorService.
| Feature | Runnable | Callable<V> |
|---|---|---|
| Package, version | java.lang, Java 1.0 | java.util.concurrent, Java 5 |
| Method | void run() | V call() throws Exception |
| Result | None | Yes, through Future.get() |
| Checked exceptions | Not allowed: InterruptedException, IOException are caught inside | Allowed: they propagate and end up in ExecutionException |
| Where to pass it | new Thread(…), execute(), submit() | submit(), invokeAll(), invokeAny(), schedule(), FutureTask |
import java.nio.file.Files;
import java.nio.file.Path;
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;
import java.util.stream.LongStream;
public class CallableExample {
public static void main(String[] args) throws InterruptedException {
Callable<Long> sum = () -> LongStream.rangeClosed(1, 1_000_000).sum();
Callable<String> config = () -> Files.readString(Path.of("missing.txt")); // IOException is allowed
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Long> sumFuture = pool.submit(sum);
Future<String> configFuture = pool.submit(config);
try {
System.out.println("Sum: " + sumFuture.get());
System.out.println("Config: " + configFuture.get());
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause());
}
}
}
} Sum: 500000500000
Task failed: java.nio.file.NoSuchFileException: missing.txt Files.readString() throws the checked IOException, and in a Runnable you would have to catch it inside the lambda. In a Callable it simply propagates, and the caller gets it wrapped in ExecutionException. Always get the original cause through getCause(): the message of the ExecutionException itself contains only the cause’s string form.
A less obvious point: which interface a lambda becomes is decided by the compiler from its body. The lambda () -> { Thread.sleep(100); } returns no value, so it only fits Runnable — and pool.submit(...) with it doesn’t compile: “unreported exception java.lang.InterruptedException; must be caught or declared to be thrown”. Add return null; and the same lambda becomes a Callable, which is allowed to throw checked exceptions. How to handle InterruptedException properly if you do catch it inside is covered in the Thread.sleep() lesson.
Future: get(), Timeouts and Cancelling a Task
Future<V> is a “receipt” for the result of a task running in another thread. get() blocks the calling thread until the result is ready, get(timeout, unit) waits no longer than the given time and throws TimeoutException, isDone() checks readiness without waiting, and cancel(true) cancels the task and interrupts the thread running it. Together, Callable and Future in Java give you what a bare Thread can’t: a return value and an exception you can inspect.
| Method | What it does | Exceptions and edge cases |
|---|---|---|
V get() | Waits for the task to finish and returns the result | ExecutionException — the task threw; CancellationException — the task was cancelled; InterruptedException — the waiting thread was interrupted |
V get(long timeout, TimeUnit unit) | Waits at most timeout | TimeoutException if the result isn’t ready; the task itself keeps running |
boolean isDone() | Whether the task has finished, without blocking | true on success, on exception and after cancellation alike |
boolean cancel(boolean mayInterruptIfRunning) | Cancels the task: if it’s still queued, it never starts; if it’s running and the argument is true, the thread gets interrupt() | false if the task has already completed; whether a running task stops depends on whether it reacts to interruption |
boolean isCancelled() | Whether the task was cancelled before it completed | — |
state(), resultNow(), exceptionNow() | Java 19: state RUNNING / SUCCESS / FAILED / CANCELLED, the result or the exception without waiting | resultNow() and exceptionNow() throw IllegalStateException if the task isn’t in the matching state |
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureTimeoutExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
Future<String> report = pool.submit(() -> {
Thread.sleep(5_000); // a "slow" report
return "report ready";
});
try {
System.out.println(report.get(1, TimeUnit.SECONDS));
} catch (TimeoutException e) {
System.out.println("No result within 1 s, isDone = " + report.isDone());
System.out.println("cancel(true) = " + report.cancel(true));
}
System.out.println("state = " + report.state()); // Java 19+
try {
report.get();
} catch (CancellationException e) {
System.out.println("get() after cancel: CancellationException");
}
}
}
} No result within 1 s, isDone = false
cancel(true) = true
state = CANCELLED
get() after cancel: CancellationException The program ends after about one second. cancel(true) interrupted the pool thread, Thread.sleep() inside the task threw InterruptedException, and the thread was freed. With cancel(false), or with no cancel at all, close() at the end of the block would wait four more seconds for the task to finish sleeping: the timeout in get() limits only the waiting, not the work.
Future also comes with a memory guarantee that rarely gets mentioned. According to the ExecutorService documentation, everything a thread does before submit() happens-before the task’s actions, and the task’s actions happen-before the return from Future.get(). So data prepared before submitting and the result obtained through get() are visible without volatile or synchronized (what happens-before means is explained in volatile in Java). The guarantee doesn’t cover shared fields that tasks modify in parallel with each other.
invokeAll() and invokeAny(): Running Several Tasks at Once
invokeAll(tasks) submits a collection of Callable objects to the pool, waits for all of them and returns a list of Future objects in the same order as the tasks. invokeAny(tasks) returns the result of the first task that completes without an exception and cancels the rest. Both methods block the calling thread and both have timeout variants.
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 InvokeAllExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Callable<String>> tasks = List.of(
() -> { Thread.sleep(300); return "warehouse A"; },
() -> { Thread.sleep(100); return "warehouse B"; },
() -> { Thread.sleep(200); return "warehouse C"; });
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
for (Future<String> f : pool.invokeAll(tasks)) {
System.out.println("invokeAll: " + f.resultNow()); // all are already done
}
System.out.println("invokeAny: " + pool.invokeAny(tasks));
}
}
} invokeAll: warehouse A
invokeAll: warehouse B
invokeAll: warehouse C
invokeAny: warehouse B The invokeAll lines follow the order of the tasks in the list, even though “warehouse B” finished first. invokeAll() returns after about 300 ms — the time of the slowest task. invokeAny() returns the fastest answer (“warehouse B” after ~100 ms; when task times are close, a different one may win) and cancels the others, which makes it a fit for querying several identical servers. If every task fails, invokeAny() throws ExecutionException.
One detail that’s easy to miss: a Future from invokeAll() may hold an exception — the method waits for completion, not for success. resultNow() is safe here only because these tasks never fail; in general, check state() or call get() inside try/catch. For a set of plain threads without a pool, a loop with join() does the same job — see join() instead of polling isAlive().
Shutting Down a Pool: shutdown() vs shutdownNow(), close()
You shut a pool down with shutdown(): it stops accepting new tasks but finishes the ones already submitted. shutdownNow() additionally interrupts running tasks and returns a list of those that never started. Neither of them waits: for waiting there is awaitTermination(), and since Java 19 close(), which calls shutdown() and waits for every task to finish.
| Method | New tasks | Already submitted tasks | Blocks the caller |
|---|---|---|---|
shutdown() | Rejected (RejectedExecutionException) | Run to completion, including the queue | No |
List<Runnable> shutdownNow() | Rejected | Running tasks get interrupt(); the queue is returned as a list and never runs | No |
boolean awaitTermination(timeout, unit) | — | Changes nothing, only waits | Yes, until the pool terminates or the timeout expires; false means it didn’t terminate in time |
close() (Java 19) | Rejected | Run to completion | Yes, with no timeout; if the waiting thread is interrupted, it calls shutdownNow() |
isShutdown() / isTerminated() | Whether shutdown() has been called / whether all tasks have finished after it | ||
Before Java 19, a proper shutdown followed the pattern from the ExecutorService documentation; you still need it today when waiting forever isn’t an option:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // stop accepting new tasks
try {
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // didn't make it - interrupt
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("Pool did not terminate");
}
}
} catch (InterruptedException e) {
pool.shutdownNow(); // we were interrupted - interrupt the tasks too
Thread.currentThread().interrupt(); // and restore the flag
}
} shutdownNow() doesn’t kill threads; it only calls interrupt() on them. A task that never checks the interrupt flag and never calls blocking methods (sleep(), wait(), BlockingQueue.take()) keeps running — hence the second awaitTermination() in the pattern. For the same reason close() hangs together with a task that never ends.
What happens if you never close the pool depends on its threads. The JVM exits when no non-daemon threads are left (the rule is explained in The main Thread and When a Program Ends):
| Pool | Threads | After main ends without shutdown() |
|---|---|---|
newFixedThreadPool, newSingleThreadExecutor, newScheduledThreadPool | Not daemons; idle threads don’t die | The program never ends |
newCachedThreadPool | Not daemons, but an idle thread dies after 60 s | The program “hangs” for about a minute after the last task, then exits on its own |
newWorkStealingPool, newVirtualThreadPerTaskExecutor | Daemons (virtual threads are always daemons) | The JVM exits right away; unfinished tasks are silently lost |
The last row is the flip side of the same problem: an unclosed pool of daemon threads doesn’t keep the program alive, but it doesn’t finish the tasks either. Try-with-resources handles both cases the same way: close() waits for the tasks and then stops the threads. A closed pool can’t be reopened — a new batch of work needs a new pool.
try-with-resources is for short-lived pools
A try (ExecutorService pool = …) block fits when the pool is created for one specific batch of work: process a file, send out requests, build a report. A pool that lives as long as the application is created once and closed when the application stops (in Spring, the container does that for you). Creating a new pool on every method call means paying for thread creation again — exactly what the pool was supposed to save you from.
ScheduledExecutorService: Scheduled Tasks
ScheduledExecutorService is a pool that runs tasks after a delay or periodically: schedule(task, delay, unit) runs a task once after the given time, scheduleAtFixedRate() runs it with a fixed period measured from the start of the runs, and scheduleWithFixedDelay() runs it with a fixed pause between the end of one run and the start of the next. It replaces a loop with Thread.sleep().
Why sleep() in a loop is a poor choice, and what scheduleAtFixedRate() looks like instead, is shown in Why sleep() in a Loop Is a Bad Way to Wait for an Event. Here is the difference between the two periodic methods:
| Method | How the interval is measured | If the task takes longer than the interval | When to use it |
|---|---|---|---|
scheduleAtFixedRate(task, initialDelay, period, unit) | From the start of the first run: 0, period, 2·period… | The next run starts right after the current one ends; two runs of the same task never overlap | You need a steady rhythm: metrics every second, timer ticks |
scheduleWithFixedDelay(task, initialDelay, delay, unit) | From the end of the previous run to the start of the next | The schedule just shifts; the pause is always at least delay | Polling an external service, cache cleanup — anything you mustn’t overload |
Both methods share one unpleasant quirk. What does this code print?
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 ScheduledFailure {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
AtomicInteger runs = new AtomicInteger();
ScheduledFuture<?> job = scheduler.scheduleWithFixedDelay(() -> {
int n = runs.incrementAndGet();
System.out.println("Run " + n);
if (n == 3) {
throw new IllegalStateException("failure on run 3");
}
}, 0, 200, TimeUnit.MILLISECONDS);
Thread.sleep(1_000);
System.out.println("isDone = " + job.isDone());
scheduler.shutdown();
}
} Run 1
Run 2
Run 3
isDone = true In one second the task should have run five times; it ran three. The exception on the third run cancelled all the following ones, and there’s no stack trace: the exception is stored in the ScheduledFuture, just as with submit(). The only way to learn about it is job.get(), which throws ExecutionException. That’s why the body of a periodic task is wrapped in try/catch (Exception e) with logging — otherwise a background job will one day quietly stop working.
Another difference from a regular pool: after shutdown(), periodic tasks are cancelled by default, while tasks delayed with schedule() still run when their time comes. You can change this with setContinueExistingPeriodicTasksAfterShutdownPolicy() and setExecuteExistingDelayedTasksAfterShutdownPolicy() of ScheduledThreadPoolExecutor.
ThreadPoolExecutor: A Pool with a Bounded Queue
ThreadPoolExecutor is the class behind almost every pool from Executors. Create it directly and you control everything: corePoolSize (core threads), maximumPoolSize (the thread limit), keepAliveTime (how long an extra idle thread lives), the task queue and the RejectedExecutionHandler — what to do with a task when the queue is full. In production it’s created explicitly to get a bounded queue.
The pool handles a new task in this order, and the order isn’t what intuition suggests:
- Fewer threads than
corePoolSize— a new thread is created, even if the others are idle. - Core threads are busy — the task goes into the queue.
- The queue is full and there are fewer threads than
maximumPoolSize— an extra thread is created. - The queue is full and the thread count is at the maximum — the task is rejected.
Hence the main subtlety: extra threads appear only when the queue is full. With an unbounded LinkedBlockingQueue the queue never fills up, and maximumPoolSize is simply never used — which is exactly how newFixedThreadPool is built.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class BoundedPoolExample {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 4, // corePoolSize, maximumPoolSize
30, TimeUnit.SECONDS, // keepAliveTime for extra threads
new ArrayBlockingQueue<>(2), // a queue for 2 tasks
new ThreadPoolExecutor.AbortPolicy()); // rejection - an exception
try (pool) {
for (int i = 1; i <= 7; i++) {
int id = i;
try {
pool.execute(BoundedPoolExample::work);
System.out.println("Task " + id + " accepted: threads " + pool.getPoolSize()
+ ", queued " + pool.getQueue().size());
} catch (RejectedExecutionException e) {
System.out.println("Task " + id + " rejected");
}
}
}
}
private static void work() {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} Task 1 accepted: threads 1, queued 0
Task 2 accepted: threads 2, queued 0
Task 3 accepted: threads 2, queued 1
Task 4 accepted: threads 2, queued 2
Task 5 accepted: threads 3, queued 2
Task 6 accepted: threads 4, queued 2
Task 7 rejected The output is the same on every run: each task sleeps for a second, so no task frees its thread while the loop is running. Look at tasks 5 and 6 — they run before tasks 3 and 4, which are waiting in the queue. Once extra threads come into play, the pool no longer guarantees FIFO order. After two seconds all six accepted tasks finish, and close() lets main go.
| Rejection policy | What it does with the extra task | When to use it |
|---|---|---|
AbortPolicy (default) | Throws RejectedExecutionException | The calling code must learn about the overload and decide itself |
CallerRunsPolicy | Runs the task in the thread that called execute() | Natural back-pressure on the task source: while it’s busy with a task itself, it sends no new ones |
DiscardPolicy | Silently drops the task | Losing it is acceptable: optional statistics, for example |
DiscardOldestPolicy | Drops the oldest task in the queue and tries again | Only fresh data matters |
The queue inside a pool is an ordinary BlockingQueue (covered in Modern Alternatives: BlockingQueue and Condition): a pool is essentially the same Producer–Consumer scheme, where your code is the producer and the pool threads are the consumers.
How to Choose the Pool Size
For computational (CPU-bound) tasks, the pool size is usually set to roughly the number of cores — Runtime.getRuntime().availableProcessors(): more threads than that can’t run at the same moment anyway. For tasks that mostly wait for the network or disk (I/O-bound), you need more threads, sometimes many times more. The exact number is found by measuring under load.
int cores = Runtime.getRuntime().availableProcessors();
ExecutorService cpuPool = Executors.newFixedThreadPool(cores); Why extra threads don’t speed up computations, and how to estimate the thread count for tasks that wait, is explained in Multithreading in Java (the formula is in its FAQ). What matters more here: keep different kinds of work in different pools. If one fixed pool of eight threads handles both calculations and calls to a slow service, eight hung calls stop all the calculations.
For I/O-bound tasks, Java 21 offers an alternative to a large pool — Executors.newVirtualThreadPerTaskExecutor(): every task gets a cheap virtual thread, and there’s no pool size to tune (what virtual threads are is explained in Platform and Virtual Threads; they will get a lesson of their own). In that case you limit resources rather than threads: the number of concurrent database queries, for example, with a Semaphore.
The next step after Future is CompletableFuture: instead of blocking in get(), you describe a chain — “when the result is ready, do this” — and it runs on the same ExecutorService.
Frequently Asked Questions
Can I submit tasks to a pool again after shutdown()?
No. After shutdown(), shutdownNow() or close(), any call to execute() or submit() throws RejectedExecutionException, and there’s no way to “restart” the pool — you create a new one. How the shutdown methods differ is shown in the table in Shutting Down a Pool.
Why does the program hang when a task waits for another task in the same pool?
This is thread starvation deadlock. In newSingleThreadExecutor(), task A submits task B to the same pool and calls b.get(): the only thread is busy with A, which waits for B, while B waits in the queue for a free thread. No exception is thrown — the program just stops. The same happens in a fixed pool of N threads if N tasks wait for nested tasks at once. Fixes: don’t block on results of tasks from your own pool, put dependent tasks in separate pools, or build chains with CompletableFuture. The classic deadlock on monitors is covered in Deadlock in Java.
How do I give pool threads meaningful names?
Pass your own ThreadFactory to the factory method. In Java 21 the easiest way to get one is from the thread builder: Executors.newFixedThreadPool(4, Thread.ofPlatform().name("order-worker-", 1).factory()) — the threads are named order-worker-1, order-worker-2 and so on. In logs and thread dumps such names tell you at once which pool is stuck, unlike a faceless pool-3-thread-2.
Is ExecutorService thread-safe? Can several threads submit tasks?
Yes, all JDK implementations are thread-safe: submit() and execute() can be called from any number of threads at once, and a single pool is usually shared across the application. The pool’s thread safety doesn’t extend to the data the tasks work with: if two tasks modify a shared counter or collection, you protect them just as you would with plain threads — see Thread Safety in Java.
Comments