Sub topic 11
Asynchronous calls with sendAsync and CompletableFuture
This chapter assumes you know the basics from earlier chapters: building an HttpClient and an HttpRequest, choosing a BodyHandler, and the checked exceptions that send throws. It also assumes a working knowledge of CompletableFuture. You should know what thenApply and join do.
Why use sendAsync
send blocks the calling thread until the response has arrived. That is simple, but the thread does nothing while it waits. sendAsync starts the request and returns at once with a CompletableFuture<HttpResponse<T>>. The future completes later, when the response (or a failure) is available.
Use sendAsync when you want to:
- start several requests and let them overlap;
- keep a thread free, for example a UI thread or a request-handling thread;
- build a pipeline of steps that run as results arrive.
If your program makes one call and then needs the answer before it can continue, send is shorter and easier to debug. Asynchronous code does not make a single request faster.
The basic shape
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class AsyncGet {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.exceptionally(ex -> {
System.err.println("Request failed: " + ex);
return null;
})
.join();
}
}Each stage does one job:
sendAsyncreturns aCompletableFuture<HttpResponse<String>>.thenApply(HttpResponse::body)turns the response into its body, giving aCompletableFuture<String>.thenAccept(System.out::println)consumes the body. It returns aCompletableFuture<Void>.exceptionallyruns only if an earlier stage failed. Returningnullsupplies theVoidresult.joinblocks until everything is finished.
The join call is there only so the demo does not exit early. In a long-running server you would not call it here.
Which thread runs your callbacks
By default the client uses an internal executor. Callbacks such as thenApply may run on one of the client's own threads. Keep those callbacks short and non-blocking. If a callback does slow work, such as a database call, it can hold up the client's threads and delay other responses.
You have two ways to move work elsewhere:
- Use the
Asyncvariants with your own executor, for examplethenApplyAsync(fn, myExecutor). - Give the client a custom executor with
HttpClient.newBuilder().executor(...). Executor configuration is covered in a later chapter.
Failures arrive inside the future
With send, failures are thrown. With sendAsync, nothing is thrown at the call site. The future completes exceptionally instead. A timeout, a connection failure or a cancelled request all end up there.
Two points matter:
- A non-2xx status is not a failure here either. The future completes normally with a response whose status is 404 or 500. Check
statusCode()in a stage. - The exception you see depends on how you read the future.
| How you read it | What you get |
|---|---|
| `exceptionally`, `handle`, `whenComplete` | Often a `CompletionException` wrapping the real cause, when the failure happened in an earlier stage of a chain |
| `join()` | Unchecked `CompletionException` with the cause attached |
| `get()` | Checked `ExecutionException` with the cause attached, plus `InterruptedException` |
The wrapping is a common source of confusion. A timeout cause is an HttpTimeoutException, but your handler may receive it wrapped. Unwrap before testing the type:
import java.net.http.HttpTimeoutException;
import java.util.concurrent.CompletionException;
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new IllegalStateException("Unexpected status " + status);
}
return response.body();
})
.handle((body, ex) -> {
if (ex == null) {
return body;
}
Throwable cause = (ex instanceof CompletionException && ex.getCause() != null)
? ex.getCause()
: ex;
if (cause instanceof HttpTimeoutException) {
return "timed out";
}
return "failed: " + cause;
})
.thenAccept(System.out::println)
.join();handle receives both the result and the exception, and exactly one of them is null. It always produces a value, so the chain continues normally afterwards. Throwing from thenApply is how you turn a bad status into a failed future, so that later stages treat it like any other error.
Running several requests at once
Because sendAsync returns immediately, a loop can start many requests before any finishes. Use one shared client so the requests can share connections.
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
List<URI> uris = List.of(
URI.create("https://example.com/a"),
URI.create("https://example.com/b"));
List<CompletableFuture<String>> futures = uris.stream()
.map(uri -> HttpRequest.newBuilder(uri).build())
.map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body))
.collect(Collectors.toList());
futures.forEach(f -> System.out.println(f.join().length()));The stream is lazy but collect forces every sendAsync call to run before the forEach. That ordering is what makes the requests overlap. If you wrote .map(...join()) inside the same stream, each request would finish before the next started, and you would lose the benefit.
In this example join throws on the first failed future, which stops the loop. To wait for all of them first, use CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(). Then read the results individually. allOf itself fails if any input fails, so attach handle to each future when you want partial results.
Cancellation and timeouts
Calling cancel(true) on the returned future marks it cancelled and the client tries to abort the request. Cancellation is best effort, and the server may already have processed the call.
Cancelling a downstream stage, such as the future returned by thenApply, does not necessarily cancel the original request. Keep a reference to the future returned by sendAsync if you need to cancel.
The timeout on HttpRequest still applies. When it expires, the future completes exceptionally with HttpTimeoutException. The timeout covers the time until the response headers arrive, not the full time to read the body. For a hard overall limit, use orTimeout(10, TimeUnit.SECONDS) on the future, available since Java 9. It completes the future with a TimeoutException, but it does not by itself abort the underlying request.
Common mistakes
- Calling
joininside a callback. Blocking inside a stage can stall the client's threads. Compose withthenComposeinstead. - Ignoring the future. If you drop the returned future without handling errors, failures disappear silently.
- Creating a client per request. Each client has its own connection pool and threads. Create one and reuse it.
- Treating
exceptionallyas a status check. It only sees exceptions. A 500 response passes straight through unless you throw. - Expecting ordered output. Futures complete in whatever order responses arrive. Read from the list in order if you need order.
Exercise
A teammate writes client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::body).exceptionally(ex -> "error"). The server returns status 503. What does the final future contain, and how would you make a 503 produce "error"?
Show answer
It contains the response body of the 503 reply, because a non-2xx status completes the future normally and exceptionally never runs. To get "error", add a check in a stage before reading the body, for example thenApply(r -> { if (r.statusCode() >= 300) throw new IllegalStateException("status " + r.statusCode()); return r.body(); }), so the future fails and exceptionally handles it.
Exercise
You start ten requests with a stream that calls sendAsync(...).thenApply(HttpResponse::body).join() inside map. Why are they not running concurrently, and what is the fix?
Show answer
Each join blocks until its request finishes before the stream moves to the next element, so the calls run one after another. Collect the futures into a list first without calling join, then join them afterwards (or use CompletableFuture.allOf).