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?
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:
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;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.