javahttpclienthttpconnection

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


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?


Solution

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


    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.