Search code examples
javahttpurlconnectionurlconnectionconnection-timeout

How the URLConnection.connectionTimeout is handled?


Given the code:

HttpURLConnection huc = (HttpURLConnection) new URL( url ).openConnection();
huc.setConnectTimeout( 10000 );
huc.connect();

how exactly the connection timeout is processed? Some HTTP header gets set or what? Or the connection status is being checked in a loop for connectionTimeout time?

I tried to find it in the source code, but there is only the long connectionTimout field...


Solution

  • Think of it as:

    Inside connect first a parallel timer is run for the the connection timeout. If the timer ends before the actual connection is established (response received), then fail.

    In reality on most platforms the operating system can be parametrised with a timeout and will handle it oneself - in the same manner. Not having seen the java native code, but there are POSIX methods like setsocketopt with which to set timeouts. POSIX connect will give a timeout.

    In java the timeout was a later much desired addition to utilize these available timeouts.