Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection timeout defaults

I seem to be having trouble with some tcp requests getting "stuck" at times, like it is waiting for some response but the connection has been "severed" so a response will never come. Is this expected behavior for HttpURLConnection with default timeouts? Are there sensible defaults set so that I can't get into this odd "hung" situation by default?

like image 605
rogerdpack Avatar asked Jul 19 '17 19:07

rogerdpack


People also ask

What is default connection timeout in Java?

There are two timeout settings: Max Wait Time: Amount of time the caller (the code requesting a connection) will wait before getting a connection timeout. The default is 60 seconds.

Does HttpURLConnection need to be closed?

Yes, it always needs to be closed.

What is http read timeout?

The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

How do I set socket timeout?

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);


1 Answers

Appears the "default" timeouts for HttpURLConnection are zero which means "no timeout."

Unfortunately, in my experience, it appears using these defaults can lead to an unstable state, depending on what happens with your connection to the server. If you use an HttpURLConnection and don't explicitly set (at least read) timeouts, your connection can get into a permanent stale state. By default. So always set setReadTimeout to "something" or you might orphan connections (and possibly threads depending on how your app runs).

It appears from trial and error that calling setConnectTimeout isn't required because the socket itself seems to have like a 2 minute "connect timeout" built in (at least in OS X).

You may also be able to set a "global default" for the timeouts by adjusting system properties.

Fix/prognosis: always set a readTimeout (even if very large), or use a different client that lets you set SO_KEEPALIVE. The default without these result in threads hanging "forever" without it (when/if they do a read), or on stale sockets sticking around forever...

like image 191
rogerdpack Avatar answered Oct 06 '22 08:10

rogerdpack