Executor choice and timeouts
What you will learn
Async suffixes let you select an execution facility. Use an owned bounded executor for finite workloads, and distinguish a caller deadline from a future completion deadline and the actual lifetime of a task.
- Inject a bounded executor into a composed workflow.
- Compare timed get, orTimeout and completeOnTimeout.
- Demonstrate overload and cleanup without blocking a constrained worker.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Inject an executor into a dependent workflow
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } }
static CompletableFuture<Integer> quote(Executor executor) { return CompletableFuture.supplyAsync(() -> 6, executor) .thenCompose(n -> CompletableFuture.supplyAsync(() -> n * 7, executor)); } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(1, 2); try { CompletableFuture<Integer> total = quote(workers); System.out.println(total.get(3, TimeUnit.SECONDS)); } finally { stop(workers); } System.out.println(workers.isTerminated()); }}Expected output:
42trueEven with one worker, the supplier returns before the dependent computation needs execution. The caller waits outside the pool and owns its cleanup.
Execution policy
supplyAsync accepts an explicit executor. Async continuations can also receive an executor; without one, ordinary CompletableFuture instances use a default facility associated with the common ForkJoinPool (Java 21 has a thread-per-task fallback when common-pool parallelism is below two). The common pool is shared; do not assume exclusive capacity or use blocking I/O indiscriminately. Non-async callbacks may run inline or on a completing thread. An Executor need not create a new thread. Inject a dedicated pool when isolation and capacity matter; only its owner shuts it down. Bounded queue rejection can occur on initial submission or during scheduling a continuation: handle both synchronous rejection and exceptional completion.
Three different deadlines
get(timeout, unit) bounds a caller wait without changing the future. orTimeout arranges exceptional completion with TimeoutException if the future is still incomplete when the deadline task wins. completeOnTimeout instead supplies a normal fallback. Both methods return and modify the original CompletableFuture, so a deadline on a shared future can affect other clients. Apply a completion deadline to a caller-specific copy when sharing the original. A deadline is not a precise scheduling guarantee and does not interrupt the supplier or prevent a late side effect. A real network or database operation needs its own timeout and cancellation strategy.
Avoid starvation and overload
A worker that calls join on a pending child queued to its own saturated pool can prevent that child from running. Instead return the child stage and compose it, then wait at the outer boundary if required. Keep asynchronous tasks finite, avoid unbounded submission, and propagate overload explicitly. Do not retry a side-effecting operation simply because a caller timed out: the first operation could still finish. For independent tasks choose measured limits on downstream resources; a larger pool does not automatically improve throughput.
A waiting deadline does not complete the future
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<Integer> result = new CompletableFuture<>(); try { result.get(0, TimeUnit.SECONDS); } catch (TimeoutException e) { System.out.println(result.isDone()); } result.complete(18); System.out.println(result.join()); }}Expected output:
false18The caller gives up its wait, but a later successful completion is still possible. Zero is used to avoid an exact timing assumption.
Apply a deadline to a caller-specific copy
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<Integer> original = new CompletableFuture<>(); CompletableFuture<Integer> view = original.copy(); System.out.println(view.orTimeout(0, TimeUnit.MILLISECONDS) == view); try { view.get(3, TimeUnit.SECONDS); } catch (ExecutionException e) { System.out.println(e.getCause().getClass().getSimpleName()); } System.out.println(original.isDone()); original.complete(25); System.out.println(original.join()); }}Expected output:
trueTimeoutExceptionfalse25The deadline mutates the copy, not the original. No competing completion can beat the timer in this controlled example. The outer timed get bounds the test wait.
Return an explicitly degraded fallback
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<String> result = new CompletableFuture<>(); System.out.println(result.completeOnTimeout("status unknown", 0, TimeUnit.MILLISECONDS).get(3, TimeUnit.SECONDS)); System.out.println(result.complete("available")); System.out.println(result.join()); }}Expected output:
status unknownfalsestatus unknownThe timeout produces a normal status, not proof of availability. A later complete call cannot replace the winning outcome. No elapsed-time measurement is asserted.
Common mistakes
Do not use the common pool as an unlimited I/O pool, block a worker on a dependent queued task, or mistake a timed-out future for a stopped task. Avoid applying completion deadlines to futures shared with other consumers. Never report a fabricated successful business result as a fallback.
Practice
Create an incomplete shared integer future and a copy. Apply completeOnTimeout(-1, 0, MILLISECONDS) to the copy, read it with a three-second deadline and print it. Print whether the shared future is done, then complete it with 7 and print its result. The -1 is an explicit unknown-status sentinel for this exercise only.
Expected output:
-1false7Compare your answer with the manual practice criteria.
Official reading: CompletableFuture · CompletionStage. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Executor choice and timeouts — knowledge check
Original asynchronous workflow questions. Java 21-compatible scope.
Which method limits only a caller wait?
What does orTimeout return?
What does completeOnTimeout do when its deadline wins?
How can a caller isolate a completion deadline from a shared future?
How should a one-worker pool handle a dependent asynchronous job?