Chris
Chris

Reputation: 3657

Does using a try-with-resource block for CloseableHttpClient also close the returning CloseableHttpResponse?

I'm trying to workout if a try-with-resource closes just the CloseableHttpClient, or also closes the response too.

For example,

private static CloseableHttpResponse sendRequest()
        throws IOException
{
    final HttpUriRequest httpUriRequest =
            buildRequest(url, requestMethod, requestParameters, httpHeaders);

    try (CloseableHttpClient client = HttpClientBuilder.create().build())
    {
        return client.execute(httpUriRequest);
    }
}

We all know this will close the CloseableHttpClient as expected. What about the result of that call though? CloseableHttpClient returns a CloseableHttpResponse. Does that also need to be closed, either in the invoking code, or somewhere else? Or is it closed at the same time as CloseableHttpClient with that try-with-resource?

Bonus question: How can I prove to myself that things are actually being closed? I'm looking at the thread pool in IntelliJ but can't quite workout where/when things are closing.

Upvotes: 1

Views: 2069

Answers (2)

ok2c
ok2c

Reputation: 27548

The answer given by Jhilton is perfectly correct (my +1). However, as far as HttpClient specific resource management is concerned closure of HttpClient instance results in closure of all kept alive and active connection, including those currently associated with HttpResponse instances. That essentially means one does not have to close HttpResponse instances if closing HttpClient instance used to execute the message exchange but such pattern is very much discouraged.

Upvotes: 2

Jhilton
Jhilton

Reputation: 405

try-with-resource will close only the resources declared in the try clause

try (CloseableHttpClient client = HttpClientBuilder.create().build())

e.g It will only close the variable "client"

Also if the response were to be closed, It would become a problem to extract the data, so the responsibility of closing it should fall elsewhere.

Upvotes: 2

Related Questions