Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
The Concurrency API for the OCP 21 exam: Executors factory methods, execute versus submit, Callable and Future, get with timeouts, ExecutionException, cancel, invokeAll and invokeAny, shutdown, shutdownNow and close, ScheduledExecutorService and virtual-thread executors.
kvi5hnuCode Sprout team member8 min readOn this page
Creating Thread objects by hand works for a few tasks. Real programs have many tasks and want to reuse threads, limit how many run at once, get results back and shut everything down cleanly. The Concurrency API in java.util.concurrent does this for you. You hand tasks to an ExecutorService, and it manages the threads. The usual advice applies for the exam and for real code: prefer an executor even when you need only one extra thread.
Getting an executor
ExecutorService is an interface. You get an implementation from the Executors factory class:
| Factory method | Returns | Threads |
|---|---|---|
newSingleThreadExecutor() | ExecutorService | one platform thread. Tasks run one at a time, in submission order. |
newFixedThreadPool(n) | ExecutorService | n reusable platform threads, with extra tasks queued |
newCachedThreadPool() | ExecutorService | creates platform threads as needed and reuses idle ones |
newSingleThreadScheduledExecutor() | ScheduledExecutorService | one platform thread that can run tasks later or repeatedly |
newScheduledThreadPool(n) | ScheduledExecutorService | n platform threads for scheduled tasks |
newVirtualThreadPerTaskExecutor() | ExecutorService | a new virtual thread for every task, with no pooling (Java 21) |
A thread pool is a set of pre-created, reusable threads. With a single-thread executor, a second task waits for the first to finish. With a pool, it can run at the same time if a thread is free. Otherwise it waits in the queue. Virtual threads are cheap, so their executor doesn't pool them.
Shutting down: always close the executor
Pool threads are non-daemon platform threads, so an executor that's never shut down keeps the JVM running after main() ends. Since Java 19, ExecutorService extends AutoCloseable, so the simplest fix is a try-with-resources block:
try (ExecutorService service = Executors.newSingleThreadExecutor()) {
service.execute(() -> System.out.println("baking"));
} // close(): stop accepting tasks, then wait for the submitted ones to finish

| Method | What happens | Accepts new tasks? | isShutdown() | isTerminated() |
|---|---|---|---|---|
| (active) | normal operation | yes | false | false |
shutdown() | queued and running tasks finish. Returns immediately. | no | true | false until all tasks end, then true |
shutdownNow() | interrupts running tasks and returns the queued, never-started ones as a List<Runnable> | no | true | false until running tasks end |
close() | shutdown(), then waits until terminated | no | true | true once it returns |
- Submitting after shutdown throws
RejectedExecutionException. awaitTermination(timeout, unit)waits up to the timeout and returnstrueif the executor terminated.shutdownNow()can only ask running tasks to stop, by interrupting them. A task that ignores interrupts keeps running.
Submitting tasks
| Method | Returns | Notes |
|---|---|---|
void execute(Runnable) | nothing | fire and forget |
Future<?> submit(Runnable) | Future<?> | get() returns null when done |
<T> Future<T> submit(Runnable, T result) | Future<T> | get() returns the given value |
<T> Future<T> submit(Callable<T>) | Future<T> | get() returns the task's result |
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>>) | List<Future<T>> | waits for all tasks. The futures are in the same order as the input. |
<T> T invokeAny(Collection<? extends Callable<T>>) | T | waits for one task to succeed and returns its result. The others are cancelled. |
invokeAll and invokeAny accept only Callables, so passing a List<Runnable> doesn't compile. Both have overloads with a timeout. If every task given to invokeAny fails, it throws ExecutionException.
Callable versus Runnable
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
A Callable returns a value and may throw checked exceptions. A Runnable does neither. This decides which submit overload a lambda matches:
service.submit(() -> 12 * 4); // returns a value: Callable<Integer>
service.submit(() -> System.out.println("hi")); // void expression: Runnable
service.submit(() -> { Thread.sleep(10); return null; }); // OK: call() may throw
service.submit(() -> { Thread.sleep(10); }); // DOES NOT COMPILE: a Runnable can't throw InterruptedException
service.execute(() -> 42); // DOES NOT COMPILE: execute takes only a Runnable
Careful: service.submit(() -> log.add("x")) is a Callable<Boolean>, because add returns a value. So its get() returns true, not null.
Future: waiting for a result
| Method | Meaning |
|---|---|
V get() | waits as long as needed, then returns the result |
V get(long timeout, TimeUnit unit) | waits at most the timeout, then throws TimeoutException (checked) |
boolean isDone() | true if the task completed normally, threw an exception or was cancelled |
boolean isCancelled() | true if it was cancelled before completing |
boolean cancel(boolean mayInterruptIfRunning) | tries to cancel it, returning false if that's no longer possible, for example because it's already done |
What get() can throw:
ExecutionException: the task itself threw. The original exception is available fromgetCause().InterruptedException: the waiting thread was interrupted.TimeoutException: only from the timed version.CancellationException(unchecked): the task was cancelled.
Java 19 added state() (RUNNING, SUCCESS, FAILED, CANCELLED) and resultNow() / exceptionNow(), which return immediately and throw IllegalStateException if the task isn't in the matching state.
The time unit for timeouts is the enum TimeUnit: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS and DAYS.
When a task throws
With submit, the exception is captured in the Future and nothing is printed. You see it only when you call get(). With execute, there's no Future, so the exception goes to the worker thread's uncaught-exception handler, which prints a stack trace. That worker thread dies, and the pool replaces it with a new one.
Scheduling tasks
ScheduledExecutorService extends ExecutorService and adds four methods. Each returns a ScheduledFuture, which is a Future plus getDelay(TimeUnit).
| Method | Effect |
|---|---|
schedule(Callable<V> task, long delay, TimeUnit unit) | runs once after the delay |
schedule(Runnable task, long delay, TimeUnit unit) | runs once after the delay |
scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) | starts a run every period, whether or not the last run took long |
scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) | waits delay after each run ends before starting the next |
try (var timer = Executors.newSingleThreadScheduledExecutor()) {
timer.schedule(() -> System.out.println("check oven"), 10, TimeUnit.SECONDS);
ScheduledFuture<String> f = timer.schedule(() -> "open shop", 8, TimeUnit.MINUTES);
} // close() waits: both delayed tasks still run, so this takes 8 minutes
- The repeating methods take only
Runnable. A lambda that returns a value doesn't compile there. - Use fixed rate for work tied to the clock, such as "every hour on the hour". If each run takes longer than the period, runs pile up: they're delayed, never executed concurrently, and the backlog can grow without limit.
- Use fixed delay when a gap between runs is what matters. A run that starts at 12, takes 5 minutes and has a 2-minute delay is followed by the next run at 12.
- Repeating tasks run until cancelled (
future.cancel(...)) or the executor shuts down: aftershutdown()they aren't run again. One-shot delayed tasks that are still waiting do still run by default aftershutdown()(shutdownNow()drops them), soclose()waits for them.
What's current
- Java 19:
ExecutorServicebecameAutoCloseable(close()), andFuturegainedstate(),resultNow()andexceptionNow(). - Java 21:
Executors.newVirtualThreadPerTaskExecutor()andExecutors.newThreadPerTaskExecutor(ThreadFactory). - Before Java 19, code had to call
shutdown()in afinallyblock. You'll still see that pattern, and it's still correct. - Structured concurrency (
StructuredTaskScope) is a cleaner way to run related subtasks, but it's still a preview feature in Java 25, so it isn't on the Java 21 exam.
Exam traps from this article
A complete example
A bakery runs its jobs through executors. The program shows the in-order processing of a single-thread executor, the results of Callable and Runnable futures, a task exception wrapped in ExecutionException, a timeout and a cancel, invokeAll and invokeAny, every shutdown method, scheduled and repeating tasks, and a timing comparison between a fixed pool of five threads and a virtual-thread-per-task executor. It uses a CountDownLatch (article 81) to wait until a task has really started.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static long timeTasks(ExecutorService service, int count, long sleepMillis) throws InterruptedException {
long start = System.nanoTime();
List<Callable<Void>> jobs = new ArrayList<>();
for (int i = 0; i < count; i++) jobs.add(() -> { Thread.sleep(sleepMillis); return null; });
service.invokeAll(jobs);
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws Exception {
System.out.println("== 1. A single-thread executor runs tasks one at a time, in order");
List<String> log = Collections.synchronizedList(new ArrayList<>());
try (ExecutorService oven = Executors.newSingleThreadExecutor()) {
oven.execute(() -> log.add("bread")); // Runnable, no Future
Future<?> cake = oven.submit(() -> log.add("cake")); // Callable<Boolean>: add() returns boolean
Future<?> pie = oven.submit(() -> { log.add("pie"); }); // Runnable: block body returns nothing
System.out.println(" cake future result: " + cake.get() + ", pie future result: " + pie.get());
} // close(): waits for all tasks
System.out.println(" baked in order: " + log);
System.out.println("\n== 2. Callable results, exceptions and Future methods");
try (ExecutorService service = Executors.newSingleThreadExecutor()) {
Future<Integer> loaves = service.submit(() -> 12 * 4);
System.out.println(" get(): " + loaves.get() + ", state: " + loaves.state());
Future<String> labelled = service.submit(() -> log.clear(), "cleared");
System.out.println(" submit(Runnable, value).get(): " + labelled.get());
Future<Integer> broken = service.submit(() -> {
if (log.isEmpty()) throw new IllegalStateException("oven too cold");
return 1;
});
try {
broken.get();
} catch (ExecutionException e) {
System.out.println(" get() threw ExecutionException, cause: " + e.getCause().getMessage()
+ ", state: " + broken.state());
}
Future<?> slow = service.submit(() -> pause(5_000));
try {
slow.get(100, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println(" get(100 ms) threw TimeoutException; isDone=" + slow.isDone());
}
System.out.println(" cancel(true): " + slow.cancel(true) + ", isCancelled=" + slow.isCancelled()
+ ", isDone=" + slow.isDone());
try {
slow.get();
} catch (CancellationException e) {
System.out.println(" get() on a cancelled task threw CancellationException");
}
}
System.out.println("\n== 3. invokeAll and invokeAny");
try (ExecutorService crew = Executors.newFixedThreadPool(3)) {
List<Callable<String>> orders = List.of(
() -> { Thread.sleep(300); return "wedding cake"; },
() -> "muffin",
() -> { Thread.sleep(100); return "baguette"; });
List<String> all = new ArrayList<>();
for (Future<String> f : crew.invokeAll(orders)) all.add(f.get());
System.out.println(" invokeAll (same order as the list): " + all);
System.out.println(" invokeAny (first to finish OK): " + crew.invokeAny(orders));
List<Callable<String>> risky = List.of(() -> { throw new Exception("burnt"); }, () -> "croissant");
System.out.println(" invokeAny ignores failed tasks: " + crew.invokeAny(risky));
}
System.out.println("\n== 4. Shutting down");
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> pause(200));
pool.shutdown();
System.out.println(" after shutdown(): isShutdown=" + pool.isShutdown() + ", isTerminated=" + pool.isTerminated());
try {
pool.submit(() -> pause(1));
} catch (RejectedExecutionException e) {
System.out.println(" submit after shutdown -> RejectedExecutionException");
}
System.out.println(" awaitTermination(5 s): " + pool.awaitTermination(5, TimeUnit.SECONDS)
+ ", isTerminated=" + pool.isTerminated());
ExecutorService busy = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
busy.submit(() -> { started.countDown(); pause(5_000); });
busy.submit(() -> pause(1));
busy.submit(() -> pause(1));
started.await();
List<Runnable> neverRun = busy.shutdownNow();
System.out.println(" shutdownNow() interrupted the running task and returned "
+ neverRun.size() + " waiting tasks; terminated=" + busy.awaitTermination(5, TimeUnit.SECONDS));
System.out.println("\n== 5. Scheduling");
try (ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor()) {
List<String> order = Collections.synchronizedList(new ArrayList<>());
ScheduledFuture<?> later = timer.schedule(() -> order.add("check oven (300 ms)"), 300, TimeUnit.MILLISECONDS);
ScheduledFuture<String> sooner = timer.schedule(() -> "open shop (100 ms)", 100, TimeUnit.MILLISECONDS);
System.out.println(" getDelay() of the later task is positive: " + (later.getDelay(TimeUnit.MILLISECONDS) > 0));
order.add(sooner.get());
later.get();
System.out.println(" ran in time order: " + order);
AtomicInteger ticks = new AtomicInteger();
CountDownLatch three = new CountDownLatch(3);
ScheduledFuture<?> rate = timer.scheduleAtFixedRate(
() -> { ticks.incrementAndGet(); three.countDown(); }, 0, 50, TimeUnit.MILLISECONDS);
three.await();
rate.cancel(false);
System.out.println(" scheduleAtFixedRate ran at least 3 times, then was cancelled: " + (ticks.get() >= 3));
}
System.out.println("\n== 6. 100 tasks that each wait 100 ms");
long fixed, virtual;
try (ExecutorService five = Executors.newFixedThreadPool(5)) {
fixed = timeTasks(five, 100, 100);
}
try (ExecutorService perTask = Executors.newVirtualThreadPerTaskExecutor()) {
virtual = timeTasks(perTask, 100, 100);
}
System.out.println(" fixed pool of 5 needs about 20 rounds: " + (fixed >= 1_900));
System.out.println(" virtual thread per task finishes in about one round: " + (virtual < 1_000));
}
}
Output:
== 1. A single-thread executor runs tasks one at a time, in order
cake future result: true, pie future result: null
baked in order: [bread, cake, pie]
== 2. Callable results, exceptions and Future methods
get(): 48, state: SUCCESS
submit(Runnable, value).get(): cleared
get() threw ExecutionException, cause: oven too cold, state: FAILED
get(100 ms) threw TimeoutException; isDone=false
cancel(true): true, isCancelled=true, isDone=true
get() on a cancelled task threw CancellationException
== 3. invokeAll and invokeAny
invokeAll (same order as the list): [wedding cake, muffin, baguette]
invokeAny (first to finish OK): muffin
invokeAny ignores failed tasks: croissant
== 4. Shutting down
after shutdown(): isShutdown=true, isTerminated=false
submit after shutdown -> RejectedExecutionException
awaitTermination(5 s): true, isTerminated=true
shutdownNow() interrupted the running task and returned 2 waiting tasks; terminated=true
== 5. Scheduling
getDelay() of the later task is positive: true
ran in time order: [open shop (100 ms), check oven (300 ms)]
scheduleAtFixedRate ran at least 3 times, then was cancelled: true
== 6. 100 tasks that each wait 100 ms
fixed pool of 5 needs about 20 rounds: true
virtual thread per task finishes in about one round: true
Points to notice:
log.add("cake")made the lambda aCallable<Boolean>, so its future returnedtrue. The block lambda{ log.add("pie"); }is aRunnable, so its future returnednull.- The exception from the task surfaced only at
get(), as the cause of anExecutionException, andstate()reportedFAILED. invokeAlllisted the results in input order, even though the "wedding cake" task finished last.- After
shutdown(),isShutdown()wastrueimmediately, butisTerminated()becametrueonly after the running task ended. shutdownNow()interrupted the running task and handed back the two tasks that never started.- A hundred 100 ms waits took about 2 seconds on five pool threads, but a fraction of a second with one virtual thread per task.
Common questions
What size should a fixed thread pool be?
For CPU-heavy work, about the number of CPUs (Runtime.getRuntime().availableProcessors()). For work that mostly waits on I/O, consider virtual threads instead of a large pool.
Is a cached thread pool unlimited? It creates threads as needed with no upper limit, and reuses or retires idle ones after 60 seconds. With many long tasks it can create a very large number of platform threads.
Can I reuse an executor after shutdown()?
No. Once shut down it can't be restarted, so create a new one.
Summary
- Get executors from
Executors: single-thread, fixed, cached, scheduled, or virtual-thread-per-task. execute(Runnable)returns nothing.submitreturns aFuture.invokeAllwaits for all tasks, andinvokeAnyreturns one result.Future.get()waits, with an optional timeout (TimeoutException). Task failures come back asExecutionException.- Shut executors down with try-with-resources (
close()),shutdown()orshutdownNow(). ScheduledExecutorServiceruns tasks after a delay, at a fixed rate, or with a fixed delay between runs.
Practice quiz
Test yourself with the ExecutorService quiz: 10 exam-style questions with explanations.
Previous: Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
Next: Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
Related reading
- Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.