Java Callable, Future and ExecutorService: Thread Pools and Task Results
Run tasks that return results with Callable and Future, then let an ExecutorService manage threads: fixed, cached and single-thread pools, virtual-thread-per-task executors, get with timeouts, cancellation, Future.state and resultNow, closing executors, and throttling with semaphores.
kvi5hnuCode Sprout team member11 min readOn this page
Creating a Thread per task, as in the previous articles, works for demos but not for real programs. Tasks usually need to return results or report failures, and creating and destroying platform threads over and over is expensive. The java.util.concurrent package answers both problems. A Callable is a task that returns a value. A Future is a handle to a result that will arrive later. An ExecutorService runs tasks for you, on a pool of reusable threads or on one fresh virtual thread per task. This is how production Java code runs concurrent work.
Callable: a task with a result
A Runnable is like a method with no parameters and no return value that runs asynchronously. A Callable<V> is the same idea, but it returns a value of type V and may throw a checked exception:
public interface Callable<V> {
V call() throws Exception;
}
A Callable<Integer> is an asynchronous computation that eventually produces an Integer. Because it is a functional interface, lambdas work, and the compiler picks Callable over Runnable when the lambda returns a value.
Future: a handle to a pending result
When you hand a task to an executor, you get a Future<V> back immediately. The task may not have started yet. The future lets you wait for the result, check on the task, or cancel it.
get()blocks until the task finishes and returns its result. If the task threw an exception,getthrows anExecutionException, with the original exception as itsgetCause(). If the task was cancelled, it throwsCancellationException. If the waiting thread is interrupted, it throwsInterruptedException.get(timeout, unit)does the same, but throwsTimeoutExceptionif the result isn't ready in time. The task keeps running.isDone()returnstrueonce the task has completed successfully, failed, or been cancelled.cancel(mayInterrupt)stops a task that hasn't started yet, so it never runs. For a running task,cancel(true)interrupts its thread, andcancel(false)lets it finish.isCancelled()reports whether the cancellation took effect.
Java 19 added three methods that make futures much more pleasant to use:
state()returns aFuture.State:RUNNING(not finished, which includes still queued),SUCCESS,FAILEDorCANCELLED.resultNow()returns the result without blocking, but only after a successful completion. Otherwise it throwsIllegalStateException.exceptionNow()returns the exception of a failed task without theExecutionExceptionwrapper.
Check state() first, then call resultNow() or exceptionNow() accordingly.
FutureTask
FutureTask<V> implements both Runnable and Future<V>. It is the adapter that lets a plain thread run a Callable while you hold a future:
var futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
Integer result = futureTask.get();
new FutureTask<>(runnable, result) wraps a Runnable and supplies a fixed result. You'll rarely use FutureTask directly, because executors do this for you.
Executors
Starting a platform thread involves the OS and isn't cheap. If a program runs many short tasks, it should reuse threads through a thread pool. A pool keeps a set of worker threads alive. You submit tasks, an idle worker runs each one, and when a task finishes the worker doesn't die but picks up the next one.
An executor is any object you submit tasks to. For platform threads that is usually a pool. For virtual threads it isn't, because virtual threads must not be pooled: they're cheap enough to create one per task.

The Executors class has factory methods for the common cases:
| Factory method | Behaviour | Good for |
|---|---|---|
newFixedThreadPool(n) | exactly n threads; extra tasks wait in an unbounded queue | CPU-bound work (n ≈ number of cores) or a crude concurrency limit |
newCachedThreadPool() | creates threads as needed, reuses idle ones, retires threads idle for 60 s | many short-lived or mostly-blocking platform-thread tasks |
newSingleThreadExecutor() | one thread runs tasks one after another, in submission order | sequential background work; measuring how much concurrency helps |
newVirtualThreadPerTaskExecutor() (Java 21) | a new virtual thread for every task | large numbers of I/O-bound tasks |
newThreadPerTaskExecutor(factory) (Java 21) | a new thread from the factory for every task | customized virtual threads |
newScheduledThreadPool(n) | runs tasks after a delay or periodically (ScheduledExecutorService) | timers, heartbeats, polling |
newWorkStealingPool() | a ForkJoinPool sized to the core count | many small CPU-bound tasks (see article 96) |
Most of these have an overload that takes a ThreadFactory, so you can name the pool's threads, which helps a lot in thread dumps and logs. For a pool, the factory should make platform threads.
Sizing and throttling
For CPU-bound tasks that compute without blocking, more threads than cores just adds context switching. A fixed pool of about Runtime.getRuntime().availableProcessors() threads gives the best throughput. For tasks that block a lot, a cached pool, or better, virtual threads, keeps the CPUs busy.
A fixed pool is also often used to throttle load. If a database tolerates only 10 concurrent queries, run them on a 10-thread pool. With virtual threads you can't do that, since there is no pool. Put a Semaphore at the point of pressure instead:
private static final Semaphore SEMAPHORE = new Semaphore(10);
String fetch(URI uri) throws IOException, InterruptedException {
SEMAPHORE.acquire(); // blocks if 10 requests are already in flight
try {
return client.send(HttpRequest.newBuilder(uri).build(), BodyHandlers.ofString()).body();
} finally {
SEMAPHORE.release();
}
}
Blocking in acquire costs a virtual thread almost nothing, and the limit applies exactly where it's needed. The demo runs 1,000 virtual-thread tasks behind a three-permit semaphore and confirms that no more than three ever run at once.
Submitting tasks
Every factory method returns an ExecutorService. You submit work with:
Future<T> submit(Callable<T> task)
Future<?> submit(Runnable task) // get() returns null
Future<T> submit(Runnable task, T result) // get() returns result
Future<?> and the Future<Void> used elsewhere in the API do the same job: they let you wait for completion or cancel the task, with no meaningful result. There's also execute(Runnable), inherited from the simpler Executor interface, which returns nothing.
Shutting down
An executor's threads keep running until you shut it down, and non-daemon pool threads will keep the JVM alive. Since Java 19, ExecutorService is AutoCloseable. close() stops accepting new tasks and blocks until all submitted tasks finish. If the closing thread is interrupted while waiting, the running tasks are interrupted too. try-with-resources makes it automatic:
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> a = executor.submit(this::loadProfile);
Future<String> b = executor.submit(this::loadOrders);
render(a.get(), b.get());
} // close(): waits for every task
Don't treat executors as precious global singletons. Creating a local executor, submitting a few tasks, and closing it is perfectly reasonable, especially with virtual threads.
For finer control, or before Java 19, there are three more methods:
shutdown()stops accepting tasks, lets queued and running tasks finish, and doesn't block.shutdownNow()stops accepting tasks, interrupts running tasks, drains the queue, and returns the tasks that never started.awaitTermination(timeout, unit)blocks until everything has finished or the timeout expires, and returns whether it terminated.
The classic pre-19 pattern is executor.shutdown(); executor.awaitTermination(10, TimeUnit.MINUTES);. Submitting to a shut-down executor throws RejectedExecutionException.
The recipe
- Get an executor from
Executors, most oftennewVirtualThreadPerTaskExecutor()for I/O-bound work ornewFixedThreadPool(cores)for CPU-bound work. submitCallableorRunnabletasks.- Keep the returned
Futures, so you can collect results, check states and cancel. - Close the executor, ideally with try-with-resources, once you're done submitting.
A complete example
The demo counts primes with Callables: first via a FutureTask on a plain thread, then split into ten tasks on a four-thread pool. It then shows a failing task, a timeout, cancellation, Java 19 future states, Runnable submissions, ordering in a single-thread executor, semaphore throttling with virtual threads, a named thread factory, and the three shutdown methods.
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
// count primes below n: a task with a result
static Callable<Integer> countPrimes(int from, int to) {
return () -> {
int count = 0;
for (int n = Math.max(2, from); n < to; n++) {
boolean prime = true;
for (int d = 2; (long) d * d <= n && prime; d++) if (n % d == 0) prime = false;
if (prime) count++;
}
return count;
};
}
public static void main(String[] args) throws Exception {
// 1. FutureTask: a Callable run by a plain thread
var futureTask = new FutureTask<>(countPrimes(0, 100_000));
new Thread(futureTask).start();
System.out.println("FutureTask result: " + futureTask.get() + " primes below 100,000");
// 2. a fixed pool, submit, and Future.get
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
var futures = new ArrayList<Future<Integer>>();
for (int i = 0; i < 10; i++) futures.add(pool.submit(countPrimes(i * 100_000, (i + 1) * 100_000)));
int total = 0;
for (Future<Integer> f : futures) total += f.get(); // blocks until each result is ready
System.out.println("10 tasks on a 4-thread pool: " + total + " primes below 1,000,000");
// 3. failure, timeout and cancellation
Future<Integer> failing = pool.submit(() -> Integer.parseInt("forty-two"));
try {
failing.get();
} catch (ExecutionException e) {
System.out.println("get() -> ExecutionException caused by " + e.getCause().getClass().getSimpleName());
}
System.out.println("state " + failing.state() + ", exceptionNow " + failing.exceptionNow().getClass().getSimpleName());
Future<String> slow = pool.submit(() -> {
Thread.sleep(Duration.ofSeconds(30));
return "too late";
});
try {
slow.get(100, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println("get(100 ms) -> TimeoutException, task still " + slow.state());
}
System.out.println("cancel(true) " + slow.cancel(true) + ", isCancelled " + slow.isCancelled()
+ ", isDone " + slow.isDone() + ", state " + slow.state());
try {
slow.get();
} catch (CancellationException e) {
System.out.println("get() on a cancelled task -> CancellationException");
}
Future<Integer> quick = pool.submit(() -> 6 * 7);
while (!quick.isDone()) Thread.onSpinWait();
System.out.println("state " + quick.state() + ", resultNow " + quick.resultNow());
// 4. Runnables: Future<?> and submit(Runnable, result)
Future<?> noResult = pool.submit(() -> { });
Future<String> fixed = pool.submit(() -> { }, "done");
System.out.println("Runnable future get: " + noResult.get() + ", with result: " + fixed.get());
} // close(): no new tasks, wait for submitted ones
// 5. a single-thread executor runs tasks one at a time, in order
var order = Collections.synchronizedList(new ArrayList<Integer>());
try (ExecutorService single = Executors.newSingleThreadExecutor()) {
for (int i = 1; i <= 5; i++) {
int n = i;
single.submit(() -> order.add(n));
}
}
System.out.println("single-thread executor order " + order);
// 6. a virtual thread per task, with a semaphore limiting concurrency to 3
var permits = new Semaphore(3);
var current = new AtomicInteger();
var peak = new AtomicInteger();
try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++)
virtual.submit(() -> {
permits.acquire();
try {
peak.accumulateAndGet(current.incrementAndGet(), Math::max);
Thread.sleep(1); // pretend to call a slow service
current.decrementAndGet();
} finally {
permits.release();
}
return null;
});
}
System.out.println("1,000 virtual-thread tasks; concurrency never exceeded 3: " + (peak.get() <= 3));
// 7. naming pool threads with a factory
ThreadFactory named = Thread.ofPlatform().name("worker-", 1).factory();
try (ExecutorService pool = Executors.newFixedThreadPool(2, named)) {
System.out.println("pool thread name starts with worker-: "
+ pool.submit(() -> Thread.currentThread().getName()).get().startsWith("worker-"));
}
// 8. shutdown, shutdownNow and rejected tasks
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> { Thread.sleep(Duration.ofSeconds(30)); return null; }); // occupies the only thread
for (int i = 0; i < 3; i++) pool.submit(() -> { }); // these wait in the queue
pool.shutdown();
try {
pool.submit(() -> { });
} catch (RejectedExecutionException e) {
System.out.println("submit after shutdown -> RejectedExecutionException");
}
List<Runnable> neverRun = pool.shutdownNow(); // interrupts the sleeper, drains the queue
System.out.println("shutdownNow returned " + neverRun.size() + " queued tasks; terminated within 5 s: "
+ pool.awaitTermination(5, TimeUnit.SECONDS));
}
}
FutureTask result: 9592 primes below 100,000
10 tasks on a 4-thread pool: 78498 primes below 1,000,000
get() -> ExecutionException caused by NumberFormatException
state FAILED, exceptionNow NumberFormatException
get(100 ms) -> TimeoutException, task still RUNNING
cancel(true) true, isCancelled true, isDone true, state CANCELLED
get() on a cancelled task -> CancellationException
state SUCCESS, resultNow 42
Runnable future get: null, with result: done
single-thread executor order [1, 2, 3, 4, 5]
1,000 virtual-thread tasks; concurrency never exceeded 3: true
pool thread name starts with worker-: true
submit after shutdown -> RejectedExecutionException
shutdownNow returned 3 queued tasks; terminated within 5 s: true
Common questions
What is the difference between submit and execute?
submit returns a Future and stores any exception in it, so you see the failure only through get() or exceptionNow(). execute returns nothing, and an exception goes to the worker thread's uncaught exception handler. Use submit when you need the result or want to handle failures yourself.
Do I have to shut down an executor?
Yes. Otherwise its non-daemon threads keep the JVM alive. Since Java 19, the simplest way is try-with-resources: close() waits for all submitted tasks to finish.
How many threads should my pool have?
For CPU-bound work, about the number of cores (Runtime.getRuntime().availableProcessors()). For work that mostly waits on I/O, use virtual threads with Executors.newVirtualThreadPerTaskExecutor(), and limit access to scarce resources with a Semaphore.
Why does my task keep running after future.cancel(true)?
Cancellation only interrupts the task's thread. If the task never checks Thread.currentThread().isInterrupted() and never calls an interruptible method, it runs to the end. The future still reports CANCELLED, and its result is thrown away.
Is newFixedThreadPool safe to use in a server?
Be careful. Its queue is unbounded, so a burst of tasks can use up all memory. For servers, construct a ThreadPoolExecutor with a bounded queue and a rejection policy such as CallerRunsPolicy.
API reference
java.util.concurrent.Callable<V>, Future<V>, FutureTask<V>
| Method | Description |
|---|---|
V call() (Callable) | computes a result, possibly throwing an exception |
V get(), V get(long time, TimeUnit unit) | waits for the result; throws ExecutionException, CancellationException, InterruptedException, or TimeoutException |
V resultNow(), Throwable exceptionNow() (Java 19) | non-blocking result or exception; IllegalStateException if not in the matching state |
Future.State state() (Java 19) | RUNNING, SUCCESS, FAILED or CANCELLED |
boolean cancel(boolean mayInterrupt) | cancels if possible; interrupts a running task if mayInterrupt |
boolean isCancelled(), boolean isDone() | status queries |
FutureTask(Callable<V> task), FutureTask(Runnable task, V result) | a Runnable that is also a Future |
java.util.concurrent.Executors
| Method | Description |
|---|---|
newCachedThreadPool(), newCachedThreadPool(ThreadFactory f) | grows as needed; idle threads end after 60 s |
newFixedThreadPool(int n), newFixedThreadPool(int n, ThreadFactory f) | n threads with an unbounded queue |
newSingleThreadExecutor(), newSingleThreadExecutor(ThreadFactory f) | one thread, sequential execution |
newVirtualThreadPerTaskExecutor() (Java 21) | a new virtual thread per task |
newThreadPerTaskExecutor(ThreadFactory f) (Java 21) | a new thread from f per task |
java.util.concurrent.ExecutorService
| Method | Description |
|---|---|
Future<T> submit(Callable<T> task), submit(Runnable task), submit(Runnable task, T result) | schedules a task and returns its future |
void close() (Java 19) | shutdown plus wait for all tasks; used by try-with-resources |
void shutdown() | no new tasks; submitted ones still run; doesn't block |
List<Runnable> shutdownNow() | interrupts running tasks, returns those never started |
boolean awaitTermination(long timeout, TimeUnit unit) | waits for termination; true if all tasks finished |
Summary
Callable<V>is a task that returns a value.Future<V>lets you wait for that value (get), poll it (state,resultNow,exceptionNow) or cancel the task.- Task exceptions surface as
ExecutionExceptionfromget. Unexamined futures hide failures. - Executors separate what to run from how. Use fixed pools for CPU-bound work, and cached pools or, better, virtual-thread-per-task executors for blocking work. Never pool virtual threads.
- Throttle virtual-thread workloads with a
Semaphore, not a small pool. - Always shut executors down, preferably with try-with-resources (
close, Java 19). UseshutdownNowto cancel, andawaitTerminationto wait with a timeout.
Practice Questions
A task submitted with submit() throws a RuntimeException. Where does the exception go?
It is stored in the returned Future. future.get() throws an ExecutionException whose cause is the original exception, and future.exceptionNow() returns it directly. If nobody inspects the future, the exception goes unnoticed.
future.get(1, SECONDS) throws TimeoutException. Is the task stopped?
No. The timeout only limits how long the caller waits. Call future.cancel(true) if you want to interrupt the task.
Why should you not use Executors.newFixedThreadPool(10, Thread.ofVirtual().factory()) to limit concurrency for virtual-thread tasks, and what should you use?
Pooling virtual threads defeats their purpose: they're cheap to create, and a pool caps the number of threads, not access to the resource you actually want to protect (tasks simply queue up without limit). Use a virtual-thread-per-task executor and a Semaphore(10) around the limited resource.
How many threads should a pool for pure CPU-bound tasks have?
About as many as there are cores, Runtime.getRuntime().availableProcessors(). More threads only add context-switching overhead.
What is the difference between shutdown() and shutdownNow()?
shutdown() rejects new tasks but lets queued and running tasks complete. shutdownNow() also interrupts running tasks and removes queued ones, returning them as a list. Neither method waits; use awaitTermination or close for that.
Previous: Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
Next: Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Related reading
- Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated
- Java Threads: Creating and Running Threads with Runnable and Thread
- Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
- Java Block Scope and if/else Statements

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.