Sub topic 10
Asynchronous calls with `sendAsync` and `CompletableFuture`
This chapter assumes you understand Java 11 syntax, HTTP methods and status codes, checked exceptions, and the basic idea of CompletableFuture. A CompletableFuture represents a result that may become available later.
How `sendAsync` works
HttpClient.sendAsync starts an HTTP request and returns immediately. It returns a CompletableFuture<HttpResponse<T>>, where T is the response-body type selected by a BodyHandler.
You can attach steps to the future:
thenApplytransforms a result.thenAcceptconsumes a result without returning another value.exceptionallyhandles a failure.joinwaits for the chain to finish.
The request itself runs asynchronously. The callback steps may run on threads managed by the HTTP client, so they should avoid blocking work.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class AsyncGet {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();
CompletableFuture<HttpResponse<String>> responseFuture =
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
responseFuture
.thenApply(response -> {
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new CompletionException(
new IllegalStateException("HTTP status: " + status));
}
return response.body();
})
.thenAccept(body -> System.out.println(body))
.exceptionally(error -> {
Throwable cause = error instanceof CompletionException
&& error.getCause() != null
? error.getCause()
: error;
System.err.println("Request failed: " + cause.getMessage());
return null;
})
.join();
}
}sendAsync does not treat an HTTP error status as a failed future. A response with status 404 or 500 still produces a normal HttpResponse. The example checks the status explicitly and throws a CompletionException so that exceptionally handles it.
Chaining and waiting
Each stage returns another future. This lets you transform data without manually creating threads.
| Operation | Purpose | Result |
|---|---|---|
| `thenApply` | Transform a value | New future |
| `thenAccept` | Use a value | Future with no value |
| `exceptionally` | Recover from failure | Replacement value |
| `join` | Wait for completion | Result or unchecked exception |
Calling join makes the current thread wait. Production applications often keep running through an event loop, server request, or other task instead. In a small command-line program, join prevents main from exiting before the asynchronous work finishes.
Several requests at once
Create one future for each request, then combine or inspect them. Starting the requests before waiting allows network operations to overlap.
flowchart LR
A[sendAsync request] --> B[CompletableFuture]
B --> C[thenApply]
C --> D[thenAccept]
B --> E[exceptionally]Exercise
Does a 404 response automatically complete the future exceptionally?
Show answer
No. The future normally completes with an HttpResponse. Check statusCode and handle non-2xx statuses yourself.