javajava-11java-http-client

Close Java HTTP Client


Is there a way to close java.net.http.HttpClient to instantly release resources held by it?

Internally it holds a selector, a connection pool and an Executor (when default one is used). However it does not implement Closeable/AutoCloseable.


Solution

  • As per Java 21, HttpClient implements AutoCloseable. It also gains the methods shutdown(), shutdownNow() and awaitTermination(), which work similarly to the same-named methods on ExecutorService.

    shutdownNow() should fill your needs.