How to test Java CompletableFuture timeout and cancellation
Java's CompletableFuture makes asynchronous code compact, but its timeout and cancellation behaviour is easy to misread. A stage can report failure to its caller while the supplier computing its value keeps running. That split matters when a test passes, a request returns an error, and a background task later charges a card or writes to a database.
Reliable tests therefore need to check more than whether a future eventually throws. They should pin down the visible completion state, the exception type, the fate of dependent stages, and whether the underlying work really stopped. These distinctions are especially important in Java and Groovy services where non-blocking I/O, scheduled jobs, and continuous delivery pipelines overlap.
Timeout and cancellation have different contracts
Start with the API contracts. orTimeout completes the selected stage exceptionally with TimeoutException when its deadline passes. cancel(true) marks that stage cancelled, and the true flag does not interrupt an already-running supplier. By contrast, Future.get(timeout) limits only the caller's wait; it leaves the future running.
| Operation | Caller-visible result | Stage state | Running supplier |
|---|---|---|---|
orTimeout(duration) |
join() throws CompletionException caused by TimeoutException |
Completed exceptionally | Continues unless stopped separately |
cancel(true) |
join() or get() throws CancellationException |
Cancelled | Is not interrupted by CompletableFuture |
Future.get(timeout) |
Caller receives TimeoutException |
May remain incomplete | Continues and may complete later |
Neither orTimeout nor cancel is a general-purpose thread-stop mechanism. If supplyAsync has started, cancelling its CompletableFuture changes the result observed by callers, but the worker can continue until it checks its own interruption flag, returns, or is stopped by separate application logic. The same applies when a timeout completes the wrapper future before its computation finishes.
Keep these outcomes separate in assertions. isCancelled() distinguishes explicit cancellation from an ordinary timeout, while isCompletedExceptionally() covers both. join() wraps most failures in CompletionException, but reports CancellationException directly. get() uses ExecutionException for a failed computation and throws TimeoutException directly when its own wait expires.
Make timeout tests deterministic
A basic timeout test should prove the failure cause, not rely on a generic exception assertion. This JUnit 5 example uses an incomplete future so no competing completion can hide the timer behaviour:
@Test
void reportsTimeoutWithoutCompletingTheValue() {
CompletableFuture<String> future = new CompletableFuture<>();
future.orTimeout(50, TimeUnit.MILLISECONDS);
CompletionException failure =
assertThrows(CompletionException.class, future::join);
assertThat(failure.getCause()).isInstanceOf(TimeoutException.class);
assertThat(future).isCompletedExceptionally();
assertThat(future).isNotCancelled();
}
The assertions observe the public contract: the stage is exceptionally complete, it is not cancelled, and the cause is TimeoutException. For a fallback, call completeOnTimeout and assert the returned value; remember that a late producer can still execute side effects even though its value will be discarded.
Avoid Thread.sleep followed by a brittle timing assertion. Use Awaitility to await a state, or get with an upper bound when a successful value is expected. Inject a ScheduledExecutorService into application timeout wrappers so a fake scheduler can fire the deadline on demand. The built-in orTimeout method does not expose its internal scheduler, which makes a thin application wrapper a useful deterministic seam.
Use elapsed durations rather than wall-clock dates. Sydney and Melbourne shift between AEDT and AEST, while Brisbane stays on AEST; a clock transition must not lengthen or shorten a timeout contract.
Cancellation is not thread interruption
cancel(true) controls the promise exposed by the future, not the worker thread. The following test deliberately starts the supplier before cancelling it, then releases that supplier after cancellation:
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean sideEffect = new AtomicBoolean();
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
started.countDown();
try {
release.await();
sideEffect.set(true);
return "late";
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new CompletionException(ex);
}
});
assertThat(started.await(1, TimeUnit.SECONDS)).isTrue();
future.cancel(true);
assertThat(future).isCancelled();
assertThatThrownBy(future::join)
.isInstanceOf(CancellationException.class);
release.countDown();
await().atMost(Duration.ofSeconds(1)).untilTrue(sideEffect);
The final wait proves that the side effect still occurred. The surrounding test should use a dedicated executor and shut it down during cleanup, but the assertion captures the crucial semantic: mayInterruptIfRunning has no practical effect on an already-running CompletableFuture supplier.
Test cancellation separately from timeout cancellation. Register a whenComplete callback, assert that it receives CancellationException, and confirm that a dependent transformation is not invoked. Also cover a supplier that has not started yet, because a cancelled asynchronous task may never enter its body.
Check dependent stages and background effects
Completion stages form another observable boundary. A stage created with thenApply after its source has been cancelled or timed out should complete exceptionally, and its mapper should not run. A callback registered with whenComplete does run for success, failure, and cancellation, so use it when an audit event must happen regardless of the outcome.
Recovery stages can change what callers see. exceptionally may turn a timeout into a cached value, while handle can inspect the cause and choose a fallback. Test the recovered value separately from the original exception; otherwise a test can accidentally approve a timeout that was silently converted into success.
Shared combinations need explicit expectations too. If one member of allOf fails, identify which aggregate state your application promises; cancelling the aggregate does not automatically cancel each member. More importantly, verify transactional boundaries. A timeout in a payment or booking flow does not reverse work already performed, so idempotency keys, transactional outbox patterns, and compensating actions deserve their own tests.
A practical testing checklist
JUnit Jupiter, AssertJ, Awaitility, and Spock can all express these contracts clearly. AssertJ's CompletableFuture assertions are convenient for state checks, Awaitility handles eventual completion without fixed sleeps, and Spock's then and thrown blocks make exception-cause assertions compact in Groovy codebases. The framework is secondary; the behavioural contract should remain identical.
- Assert the stage state and exception cause separately, including
isCancelled()for explicit cancellation. - Use latches or Awaitility rather than fixed sleeps to coordinate asynchronous execution.
- Give real-time tests generous upper bounds and await the eventual outcome.
- Cover timeout, fallback, pre-completed stages, cancellation, and recovery branches separately.
- Verify that downstream transformations do not run while
whenCompletefollows its documented contract. - Prove whether underlying work stopped, adding idempotency or compensation checks where it may continue.
- Inject clocks and schedulers into application wrappers for deterministic deadline tests.
Apply the same suite at unit, integration, and pipeline levels, but keep real-time waits concentrated in a small number of tests. In a busy continuous delivery runner, a 20-millisecond deadline may be delayed by garbage collection. Prefer a fake scheduler for branch coverage and retain a few genuine asynchronous tests to catch integration mistakes. Repeating those tests under modest parallel load can expose flakiness before it reaches an Australian team's production release window.
Design for explicit completion contracts
Context changes the risk, not the Java semantics. Australian banking, government, logistics, and ecommerce platforms often coordinate services across Sydney, Melbourne, Brisbane, and Perth. A morning stand-up in Perth can occur before Sydney's morning stand-up, so elapsed-time tests and explicit deadlines are safer than assumptions about local clock times.
Test data also deserves local care. Systems handling identifiers, transaction histories, or support records may fall under the Privacy Act 1988 and the Australian Privacy Principles. Synthetic fixtures and masked production samples reduce exposure, while a stable data generator makes timeout retries reproducible without retaining personal information.
Treat timeout, cancellation, and business compensation as three separate capabilities. Document which one the API offers, verify the exact exception and stage state, and confirm whether background work can still finish. In distributed Australian teams, that clarity prevents a deadline from being mistaken for a rollback. The behaviour to remember is simple: changing a CompletableFuture's completion does not, by itself, stop work already running.