I'm using JDK HttpClient to make some asynchronous HTTP requests. In particular I have a class similar to the following one:
public class MyClass {
private HttpClient client;
public MyClass(){
client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(20))
.build();
}
public void send(String url){
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
}
}
This way, when invoking to the send method I'm reusing the client attribute. According to the doc this is valid because: "Once built, an HttpClient is immutable, and can be used to send multiple requests".
Together with this I have an in-memory cache where I'm keeping instances of MyClass. I would like to know if this is a good practice or not. In particular I would like to know if retaining those references to the HttpClient client attribute in memory may cause any kind of memory leak or problem like the one mentioned here.
Could this for example be a problem for releasing/ending the thread executor that is used for executing asynchronous requests?