Search code examples
javaapache-httpclient-4.xelasticsearch-jest

Should we not be closing the connection after response in JestHttpClient for elastic search


This is with respect to the code at https://github.com/searchbox-io/Jest/blob/master/jest/src/main/java/io/searchbox/client/http/JestHttpClient.java

In this code snippet

public <T extends JestResult> T execute(Action<T> clientRequest) throws IOException {
    HttpUriRequest request = prepareRequest(clientRequest);
    HttpResponse response = httpClient.execute(request);

    return deserializeResponse(response, request, clientRequest);
}

private <T extends JestResult> T deserializeResponse(HttpResponse response, Action<T> clientRequest) throws IOException {
    StatusLine statusLine = response.getStatusLine();
    return clientRequest.createNewElasticSearchResult(
            response.getEntity() == null ? null : EntityUtils.toString(response.getEntity()),
            statusLine.getStatusCode(),
            statusLine.getReasonPhrase(),
            gson
    );
}

After we receive the response should we not be doing something like

response.close()

This particular stack overflow thread HttpClient 4.0.1 - how to release connection? mentions about consuming the response entity using

EntityUtils.consume(HttpEntity)

Would just doing EntityUtils.toString(response.getEntity()) suffice ?


Solution

  • EntityUtils.toString(response.getEntity()) will suffice if it can finish successfully. If an UnsupportedEncodingException is throw for instance, the response will not be read by toString and connection will be blocked. My suggestion is to call EntityUtils.consume(HttpEntity) in finally block to prevent hanging connections.