Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Is it a good practice to define java.net.http.HttpClient instance attributes?

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?

over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda