Sub topic 10
Setting connect and request timeouts
This chapter assumes you can build an HttpClient and an HttpRequest, send a request with send, and catch checked exceptions. The async section also assumes basic CompletableFuture use.
By default, an HttpClient waits forever. If a server accepts your connection and never answers, your thread blocks indefinitely. Timeouts are the main defence against that, and the API gives you two of them with different scopes.
Two timeouts, two scopes
| Timeout | Set on | Covers | Exception |
|---|---|---|---|
| Connect timeout | `HttpClient.Builder.connectTimeout` | Establishing a new connection to the server | `HttpConnectTimeoutException` |
| Request timeout | `HttpRequest.Builder.timeout` | The wait from sending the request until the response arrives | `HttpTimeoutException` |
Both take a java.time.Duration. Both default to "no timeout". A zero or negative duration throws IllegalArgumentException when you build the client or request.
The connect timeout belongs to the client, so every request made through that client shares it. The request timeout belongs to one request, so each call can use a different value.
The block above is intentionally not used. The diagram follows.
Setting both timeouts
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
public class TimeoutDemo {
public static void main(String[] args) {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
} catch (HttpConnectTimeoutException e) {
System.err.println("Could not connect in time: " + e.getMessage());
} catch (HttpTimeoutException e) {
System.err.println("No response in time: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Interrupted");
}
}
}The catch order matters. HttpConnectTimeoutException extends HttpTimeoutException, which extends IOException. Java requires the most specific type first. If you only need one "timed out" branch, catch HttpTimeoutException alone.
What the request timeout does and does not cover
The request timer starts when you call send or sendAsync. It includes time spent connecting, so a request with a 5-second timeout and a 2-second connect timeout can spend at most 2 seconds connecting.
The documentation describes the request timeout as the time to receive "the response". In the JDK implementation, the timer stops once the response headers arrive. A server that sends headers quickly and then trickles the body very slowly is therefore not stopped by it. Check this on the JDK version you deploy, because it is an implementation detail rather than something the API promises.
There is also no per-read socket timeout. If you need a hard limit on the total time, including the body, enforce your own deadline.
Enforcing a total deadline
Run the request with sendAsync and wait on the future with a limit. When the wait expires, cancel the future.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TotalDeadline {
public static void main(String[] args) throws InterruptedException {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/")).build();
CompletableFuture<HttpResponse<String>> future =
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
try {
HttpResponse<String> response = future.get(8, TimeUnit.SECONDS);
System.out.println("Status: " + response.statusCode());
} catch (TimeoutException e) {
future.cancel(true);
System.err.println("Gave up after 8 seconds in total");
} catch (ExecutionException e) {
System.err.println("Request failed: " + e.getCause());
}
}
}Note the two different timeout types here. java.util.concurrent.TimeoutException comes from the future.get deadline. HttpTimeoutException comes from the HTTP client itself. They are unrelated classes, so a catch for one never catches the other.
Timeouts with sendAsync
With sendAsync the failure does not throw at the call site. The future completes exceptionally, and the HTTP exception is often wrapped in a CompletionException. Unwrap it before testing its type.
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.exceptionally(ex -> {
Throwable cause = (ex instanceof java.util.concurrent.CompletionException && ex.getCause() != null)
? ex.getCause()
: ex;
if (cause instanceof java.net.http.HttpConnectTimeoutException) {
System.err.println("Connect timed out");
} else if (cause instanceof java.net.http.HttpTimeoutException) {
System.err.println("Request timed out");
} else {
System.err.println("Failed: " + cause);
}
return null;
})
.join();Common mistakes
- Setting only the request timeout. It does bound connecting, but you lose the ability to tell a dead host from a slow server. Set both so the error tells you which one happened.
- Assuming the connect timeout applies to every request. It applies only when a new connection is opened. Requests that reuse a pooled connection never hit it. With HTTP/2, many requests can share one connection.
- Building a new client per request to vary the connect timeout. This throws away connection reuse. Keep one shared client and vary the per-request timeout instead.
- Treating a timeout as proof the server did nothing. The server may have received and processed the request. Retrying a non-idempotent
POSTafter a timeout can create duplicates. - Confusing timeouts with idle keep-alive. The system property
jdk.httpclient.keepalive.timeoutcontrols how long idle pooled connections stay open. It has no effect on how long your calls wait.
Choosing values
Pick values from the service you call, not from habit. A connect timeout of 2 to 5 seconds suits most networks, because connecting to a healthy host is fast. Request timeouts depend on the endpoint. A health check may need 1 second, while a report generator may need 60. Setting a request timeout per call, based on what that call does, is more accurate than one global number.
Exercise
Your client sets connectTimeout to 3 seconds. A request through it sets timeout to 10 seconds. The server is reachable and accepts the connection immediately, but never sends any response. After about how long does the call fail, and with which exception type?
Show answer
After about 10 seconds, with HttpTimeoutException. The connection succeeded, so the connect timeout never fires. Only the request timeout, which waits for the response, expires. It is not an HttpConnectTimeoutException.
Exercise
A server sends response headers at once, then sends the body at one byte per second. The request has timeout(Duration.ofSeconds(5)). Will the request timeout stop the call? What can you do to bound the total time?
Show answer
In the JDK implementation the request timer stops when the headers arrive, so it will likely not stop the call, though you should verify this on your JDK version. To bound the total time, use sendAsync and call future.get with a deadline, then cancel the future with future.cancel(true) if a TimeoutException occurs.