How to close HttpClient? Why there is no .close() method in the API?

903 views Asked by At

I want to use so called "new HttpClient since Java 11" java.net.http.HttpClient.

To me, it is very important to make sure that the TCP connection gets closed after an HTTP roundtrip completes, so that corresponding port gets released and resources - deallocated.

There is no .close() or .disconnect() or something like that available on the API.

It is very weird not to have a possibility to close the connection, and it is also weird why the expected behaviour (what is happening? is the connection getting closed automatically? when? how?) is never documented anywhere, including Introduction to the Java HTTP Client and Examples and Recipes .

Any tips?

2

There are 2 answers

0
Giorgi Tsiklauri On BEST ANSWER

Finally, since the Java 21 LTS, the java.net.http.HttpClient is now AutoCloseable, and the following methods have been added to the API:

  • void close() - closes the client gracefully, waiting for submitted requests to complete;
  • void shutdown() - initiates a graceful shutdown, then returns immediately without waiting for the client to terminate;
  • void shutdownNow() - initiates an immediate shutdown, trying to interrupt active operations, and returns immediately without waiting for the client to terminate;
  • boolean awaitTermination(Duration duration) - waits for the client to terminate, within the given duration; returns true if the client is terminated, false otherwise;
  • boolean isTerminated() - returns true if the client is terminated.

Two additional notes:

  1. The instances returned by HttpClient.newHttpClient(), and the instances built from HttpClient.newBuilder(), provide a best effort implementation for these methods. They allow the reclamation of resources allocated by the HttpClient early, without waiting for its garbage collection;
  2. An HttpClient instance typically manages its own pools of connections, which it may then reuse when necessary. Connection pools are typically not shared between HttpClient instances. Creating a new client for each operation, though possible, will usually prevent reusing such connections.
2
Holger On

This is indeed a missing feature and you’ll have to wait for Java 21 to be able to close HttpClient explicitly.

See bug report JDK-8304165, “Support closing the HttpClient by making it auto-closable”:

Make the java.net.http.HttpClient implement AutoCloseable in order to make it possible to reclaim its resources early (selector, idle connections sitting in pools, etc...) rather than having to wait for GC to garbage collect it.

It has the status “Approved” and Fix Version 21. You can also verify with the early access documentation of HttpClient which shows that it now implements AutoCloseable and therefore has a close method which also says “Since: 21”.