Skip to content

HTTP client lifetime (ARCH4083)

Key java.performance.http-client-lifetime · Severity error · Category performance

Creating a new HttpClient per call rebuilds the connection pool and accumulates sockets in TIME_WAIT. The client should be a shared singleton.

public String fetch(String url) throws Exception {
HttpClient client = HttpClient.newHttpClient();
return client.send(request(url), ofString()).body();
}
private static final HttpClient CLIENT = HttpClient.newHttpClient();
public String fetch(String url) throws Exception {
return CLIENT.send(request(url), ofString()).body();
}

Hold a single HttpClient instance in a shared field and reuse it across all requests.