Sindhu
Sindhu

Reputation: 2582

How to Handle HttpAsyncClient exception

I want to understand few basic concepts about HttpAsyncClient .

  1. I am not using connection pool here , What is the correct way to close failed http request here (1) or (2) .

  2. What are the performance implications here ,if I Initialize httpclient with each new request ?

  3. Do I need to close the connection in finally block for all the failed requests , What is the drawback of not doing so ?


RequestConfig config = RequestConfig.custom()
    .setConnectTimeout(3 * 1000)
    .setConnectionRequestTimeout(3 * 1000)
    .setSocketTimeout(30 * 1000)
    .build(); 

CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
    .setDefaultRequestConfig(config)
    .build();

httpclient.start();

try {

    if (targetHost != null && httpget != null)
        response = httpclient.execute(HttpHost, HttpGet);
    catch (Exception e) {

        throw new CustomException("service.unavailable");

    } finally {
        if (httpget != null){
            httpget.releaseConnection(); (1)
            httpclient.close();(2)
        }

    }

Upvotes: 0

Views: 942

Answers (1)

Edward B.
Edward B.

Reputation: 439

Everything looks OK at first glance. I would get rid of the httpget.releaseConnection(), it is not necessary. Running the close statement will take care of everything you need and also free the thread running the connection. That kind of answers your third question; closing the connection will free the resources attached to it.

As for initializing a new connection each request; I wouldn't be so concerned with resources as the response of the servers/websites you are connecting to with this. Opening any web request takes time not really on your behalf but the server and waiting for responses and things to happen. I would write an optimized function with all of the handling of the web request and call that for each one, as it would open up the door to make this a multi-threaded application where multiple connections can be established while others are busy.

Upvotes: 1

Related Questions