AutoCloseable HttpClient - Sip of Java

HttpClient has been updated to be AutoCloseable in Java 21. Let’s take a look!

AutoCloseable

AutoCloseable is not a new feature; it was initially introduced in JDK 7 for use with try-with-resources statements. Classes implementing AutoCloseable provide a close() method to release and/or dispose of underlying resources like database connections or file sockets from an object. The JDK would automatically call the close() method for resources declared in the header of try-with-resources on completion of the statement. This provided better assurance of the prompt release of resources.

AutoCloseable in HttpClient

The Java Bugs System (JBS) Issue JDK-8267140 defined making HttpClient AutoCloseable, which added five new methods to HttpClient:

  • 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.

The instances of HttpClient returned from HttpClient.newHttpClient() and HttpClient.newBuilder() provides a best attempt at implementing these methods. However, if different behavior is needed, then HttpClient can be extended, and method(s) overridden to provide more appropriate behavior for your needs.

Properly Closing HttpClient

Before JDK 21, HttpClient didn’t provide documentation on when it would release resources like connections, which caused confusion about when precisely these resources would be released. This led to questions in Stack Overflow threads and 3rd-party libraries, like Apache HttpClient, implementing their own close() methods.

For clarity, the documentation of HttpClient was updated to detail its behavior for closing connections. In addition, updating HttpClient to be AutoClosable should result in more prompt releasing of resources as the resources should be released at the end of the try-with-resources statement instead of when the HttpClient object is garbage collected.

Additional Reading

HttpClient JDK 21 Javadoc

Happy coding!