URLConnection getInputStream Hangs
This post is probably just interesting for Java-nerds. And by that I don’t mean people who are crazy about coffee. I have a friendly suggestion for you if you’re using the Java class URLConnection and any JDK prior to 1.5:
Stop using it!
The getInputStream method will block if anything goes wrong with the connection and the thread calling it will lock up. There is no way of setting a timeout, and if for instance have a single threaded monitor process (because you really don’t have the need to do anything in parallel) and you don’t have a control thread checking the aliveness of the main thread - you’re basically fucked. Just like I was for a while until I figured out what was going on.
Prior to monitoring, the service had to contact another server to authenticate, and the authentication server wasn’t always playing by the book. When that happened, the getInputStream method locked everything and the monitoring service failed for no apparent reason. Hooray!
Fortunately, Java 1.5 (or 5.0, whatever you prefer) solves the problem by adding a setReadTimeout method. This method throws a SocketTimeoutException if the getInputStream method times out, and saves the day.
See URLConnection (Java 2 Platform SE 5.0) for more information.
Today Mew released their new album “Mew And The Glass Handed Kites”. Haven’t bought it yet, but probably will head out in a few minutes to do it. Probably have a short run after that.
Feedback
Do you have any thoughts you want to share? A question, maybe? Or is something in this post just plainly wrong? Then please send an e-mail to vegard at vegard dot net
with your input. You can also use any of the other points of contact listed on the About page.
Is there another way around other than going to Java 1.5? Unfortunately I need to stay on 1.4 for the time being? I had heard that this could be averted by adding Content-Length to the response since getInputStream is blocking on a completing the response.
Could be that you can set the Content-Length header on the server side to save the day, but in some cases you don’t have any control of the server side.
Oh man, you saved my life :D I was totally knocked out, debugging mysterious deadlock for ages, but google and this socket error solved my problem ;]
Thx again!!
thanks, this info was very helpful!
Thanks.
This just happen to me.
Something I wrote almost 8 years ago turned out to be useful for someone? That’s the power of the interwebs!
We just got nailed on this too, now are setting both read and connect timeouts
Thanks.
Saved my ass ;)