Search code examples
javaapache-httpclient-4.xapache-httpasyncclient

Unable to set Socket Timeout less than 1000 milliseconds in RequestConfig (Apache HTTP async client 4.1.2)


Following is my code

       RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(100)
                .setConnectTimeout(100)
                .setConnectionRequestTimeout(100).build();


        CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        httpClient.start();

According to setSocketTimeout value, it should timeout in 100 ms, but it is taking 1000 ms to timeout. setSocketTimeout is honouring all value greater than 1000 ms, though.


Solution

  • This behavior is intentional. The i/o selector threads need to iterate over existing i/o sessions on a regular basis and trigger socket timeout event in case of i/o inactivity. This operation can get very expensive especially as the number of concurrent sessions grows. By default the i/o select interval is set to 1000 ms, and therefore the granularity of socket timeout by default is 1 sec. One can reduce the select interval and make i/o selector threads iterate over sessions more often at the cost of greater CPU utilization. With select interval of 1ms i/o selector threads will effectively run in a busy loop.

    IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
            .setSelectInterval(100)
            .setSoTimeout(100)
            .setConnectTimeout(100)
            .build();
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
            .setDefaultIOReactorConfig(ioReactorConfig)
            .build();