Sub topic 15
Reusing one client and running requests concurrently
This chapter assumes you can build an HttpClient and a request, call send and sendAsync, and use basic CompletableFuture methods such as thenApply and join. It covers why one client should serve your whole application, how to run many requests at once, and how to keep that concurrency under control.
What a client owns
An HttpClient is more than a settings holder. Each instance manages:
- a pool of open connections to servers, kept alive for reuse
- a background selector thread that watches those connections for I/O events
- an executor that runs asynchronous completion steps
- its configuration: timeouts, redirect policy, version, proxy, cookie handler and authenticator
Once built, a client is immutable and safe to use from many threads at once. You can call send and sendAsync on the same instance concurrently without locking.
Creating a client per request throws away the connection pool. Every call then pays for a new TCP connection and TLS handshake, and every client starts its own selector thread. In a busy service this wastes time and threads.
// Avoid: a new client, pool and selector thread for every call
HttpResponse<String> bad(HttpRequest request) throws Exception {
return HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
}Sharing one client
The simplest pattern is a single static final field, or one instance created at startup and passed to the classes that need it (for example through dependency injection).
import java.net.http.HttpClient;
import java.time.Duration;
public final class Api {
public static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
private Api() {}
}Settings that belong to the client, such as redirects, proxy and authenticator, apply to every request it sends. If two groups of calls need different client-level settings, build two clients. Per-request settings such as the timeout, headers and URI go on the HttpRequest.
An HttpRequest is also immutable, so you can build it once and send it many times.
The diagram below shows the shape of the pattern.
Running requests concurrently
sendAsync returns a CompletableFuture immediately, so you can start many requests before any of them finishes. The example below fetches several URLs in parallel. Each future converts its own outcome, success or failure, into a result string with handle. That way one failed request does not hide the others.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class ConcurrentFetch {
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
static CompletableFuture<String> fetch(URI uri) {
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(10))
.GET()
.build();
return CLIENT.sendAsync(request, BodyHandlers.ofString())
.handle((response, ex) -> ex == null
? uri + " -> " + response.statusCode()
: uri + " failed: " + ex);
}
public static void main(String[] args) {
List<URI> uris = List.of(
URI.create("https://example.com/"),
URI.create("https://example.org/"),
URI.create("https://example.net/"));
List<CompletableFuture<String>> futures = uris.stream()
.map(ConcurrentFetch::fetch)
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
futures.forEach(f -> System.out.println(f.join()));
}
}Three points about this code:
allOfcompletes when every future has completed. It returnsCompletableFuture<Void>, so you read each result from the original futures afterward.- If you skip
handleand one future fails,allOf(...).join()throws aCompletionExceptiononce all futures finish. The successful results are still available from their own futures, but you must check each one. join()blocks the calling thread. Do it at the edge of your program, not inside another async step.
Choosing a concurrency style
| Style | How it works | Use when |
|---|---|---|
| Sequential `send` | One request after another on one thread | Order matters, or there are only one or two calls |
| `sendAsync` plus `allOf` | Requests overlap, no extra threads on your side | Many independent calls, results combined at the end |
| `send` in your own thread pool | Each task blocks on its own thread | Existing blocking code, or you want a hard cap on parallelism |
Limiting how many requests run at once
HttpClient does not cap the number of in-flight requests you start. With HTTP/1.1, a large burst can open many connections to one host. With HTTP/2, requests to one host are multiplexed over a single connection, but the server may still limit concurrent streams. Servers and rate-limited APIs may reject or throttle a burst, so you often need your own limit.
A Semaphore is the simplest tool. Acquire a permit before sending and release it when the future completes. This method reuses fetch from the previous example.
import java.util.concurrent.Semaphore;
private static final Semaphore PERMITS = new Semaphore(4);
static CompletableFuture<String> fetchLimited(URI uri) throws InterruptedException {
PERMITS.acquire();
try {
return fetch(uri).whenComplete((result, ex) -> PERMITS.release());
} catch (RuntimeException e) {
PERMITS.release();
throw e;
}
}acquire blocks the submitting thread when four requests are already running. That slows down the loop that starts requests, which is the intended back-pressure. The catch block releases the permit if the request cannot even be started, for example when building it throws.
The executor and blocking code
By default the client uses an internal cached thread pool to run the steps you chain onto a future, such as thenApply and handle. A cached pool creates threads on demand, so slow blocking work inside those steps can multiply threads. You can supply your own pool with HttpClient.newBuilder().executor(...).
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService pool = Executors.newFixedThreadPool(8);
HttpClient client = HttpClient.newBuilder().executor(pool).build();If you provide an executor, you own its lifecycle. The client does not shut it down. Also keep steps short. Do not run database queries or other slow blocking calls inside thenApply on the client's executor. Hand that work to a separate pool with thenApplyAsync(fn, otherExecutor).
Client lifetime and cleanup
In Java 11 through 20, HttpClient has no close method. Idle connections and the selector thread are released when the client is no longer referenced and garbage collected, which is another reason to keep one long-lived instance. Java 21 added close, shutdown and shutdownNow and made the class AutoCloseable. Do not wrap a shared, application-wide client in try-with-resources, because that closes it for everyone.
Common mistakes
- Creating a client per request. You lose connection reuse and add threads.
- Using
allOfwithout per-future handling. One failure turns the combined result into an exception, and you lose track of which requests succeeded. - Blocking with
joininside async steps. This can stall threads on the client's executor. - Starting thousands of requests with no limit. You can overload your own process or the target server.
- Assuming a shared client shares request state. It does not. Cookies are shared only if you configured a
CookieHandler, so be careful when one client serves several users.
Exercise
A service calls an API using a helper method that begins with HttpClient client = HttpClient.newHttpClient(); and then sends one request. Under load, latency is high and the thread count keeps growing. What change fixes this, and why does it help?
Show answer
Move the client into a single long-lived instance, such as a static final field or an injected singleton, and have the helper use it. Every call currently gets a new connection pool and selector thread, so each request pays for a fresh TCP and TLS connection and adds a thread. A shared client reuses pooled connections and uses one selector thread. It is thread-safe, so concurrent callers can share it.
Exercise
You start 200 sendAsync calls in a loop against one rate-limited API, and the server begins returning 429 responses. Name one way to cap concurrency to 10 in-flight requests, and say where the permit must be released.
Show answer
Use a Semaphore with 10 permits. Call acquire() before each sendAsync, and release the permit in whenComplete (or handle) on the returned future so it is released on both success and failure. Also release it if starting the request throws before a future is returned.