Sub topic 14
Reusing One Client and Running Requests Concurrently
Assume you know how to build an HttpClient, create an HttpRequest, and use CompletableFuture. This chapter shows how to reuse one client safely and start several HTTP calls without waiting for each call to finish.
Why reuse one client?
HttpClient is designed to be reused. A shared client can manage connections, connection pools, and configuration for many requests. Creating a new client for every request adds overhead and can prevent effective connection reuse.
A client is safe to use from multiple threads. Keep one configured instance for an application component, such as an API service, and use it for all related requests.
| Object | Usually reused? | Purpose |
|---|---|---|
| `HttpClient` | Yes | Connections and client configuration |
| `HttpRequest` | No | One request's URI, method, and headers |
| `HttpResponse` | No | One completed response |
Starting requests concurrently
A synchronous call blocks the current thread until its response arrives. If you send three requests synchronously, the second starts only after the first finishes.
sendAsync starts a request and returns a CompletableFuture. The future represents a result that may arrive later. Creating several futures first lets the operations overlap.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ConcurrentGets {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder().build();
List<URI> uris = List.of(
URI.create("https://example.com/"),
URI.create("https://example.com/about"),
URI.create("https://example.com/contact"));
List<CompletableFuture<HttpResponse<String>>> futures = uris.stream()
.map(uri -> HttpRequest.newBuilder(uri).GET().build())
.map(request -> client.sendAsync(
request, HttpResponse.BodyHandlers.ofString()))
.toList();
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join();
futures.forEach(future -> {
HttpResponse<String> response = future.join();
System.out.println(response.statusCode()
+ " " + response.uri());
});
}
}The calls begin as the stream creates the futures. allOf produces a future that completes when every supplied future completes. Calling join then waits for the group. Individual join calls retrieve each response.
Handling concurrent failures
A failed request completes its future exceptionally. For production code, handle failures per request so one failed operation does not hide useful results from the others.
A shared client does not mean shared mutable request state. Build each HttpRequest with its own URI, headers, and body. Also avoid unbounded concurrency. A large collection of requests can consume memory, sockets, and server capacity. Use batches or a bounded application-level executor when the input is large.
Exercise
Why is one shared HttpClient usually better than creating one client per request?
Show answer
It allows connection reuse and avoids repeatedly creating client resources, while remaining safe for concurrent use.