Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda