8

I have this code:

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(40 * 1000)
            .setConnectionRequestTimeout(40 * 1000)
            .setSocketTimeout(40 * 1000)
            .build();
    client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .build();
}

and

    try {

        Stopwatch stopWatch = Stopwatch.createStarted();
        response = client.execute(new HttpGet(routingRequestUrl));
        stopWatch.stop();

    } catch (Exception e) {
        answer.errorMsg = e.getMessage();
        answer.latency =  null;
    }

when my client configuration is as doesn't contain .setSocketTimeout(40 * 1000) - the stopWatch shows request can take more then 1 minute.

It happens when I try setConnectTimeout and setConnectionRequestTimeout each alone or all together.

Why is only .setSocketTimeout(40 * 1000) effectively checks timeout 40 seconds? and the other alone not?

These are the prints:

Read timed out

Timeout waiting for connection from pool

Is the first triggered by setConnectionRequestTimeout and the second by setSocketTimeout ?

Elad Benda2
  • 13,852
  • 29
  • 82
  • 157
  • See also [understanding URLConnection.setReadTimeout()](https://stackoverflow.com/questions/24554342/understanding-urlconnection-setreadtimeout) – Vadzim Nov 27 '18 at 21:16

1 Answers1

24

https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.html

getConnectionRequestTimeout()

Returns the timeout in milliseconds used when requesting a connection from the connection manager.

getConnectTimeout()

Determines the timeout in milliseconds until a connection is established.

getSocketTimeout()

Defines the socket timeout (SO_TIMEOUT) in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets).

__

So, the first one, connectionRequestTimeout happens when you have a pool of connections and they are all busy, not allowing the connection manager to give you one connection to make the request.

connectTimeout happens when establishing the connection. For instance while doing the tcp handshake.

socketTimeout like the description says, is the timeout while waiting for data. Usually happens when your server is slow.

Paulo Santos
  • 661
  • 7
  • 11
  • so if i want to terminate request that didn't return after 40 seconds I should use socketTimeout only ? – Elad Benda2 Jul 24 '15 at 21:01
  • 4
    @EladBenda2 unfortunately not, you will need create you're own wrapper that does an overall that could encompass the `connectionRequestTimeout`, `connectTimeout` and `socketTimeout`. The `socketTimeout` is the time in seconds between receiving bytes of data, so as long as you are receiving data it won't timeout. – Welsh Oct 30 '17 at 21:02