5

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
caristu
  • 115
  • 1
  • 5
  • 2
    Well - it depends. It's not a good practice to create one client per request, as creating a client is rather expensive. On the other hand, the resources held by the HttpClient will only be released after all in flight requests/operations are finished, *and* all references to the HttpClient have been released. So if there is a point in time where you know that you will no longer need the client, you should put all its references to null (or release all objects that have a reference on it). But as a general rule, then one client per request is a bad idea. – daniel Mar 21 '22 at 16:12
  • Thank you for the response. Its clear. I'll take it into account. I've tried to find documentation about good practices for using HttpClient but unfortunately I've not been able to find any resources so far. – caristu Mar 23 '22 at 09:11

0 Answers0