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.

Caution

It looks like you're using Google's Chrome browser, which records everything you do on the internet. Personally identifiable and sensitive information about you is then sold to the highest bidder, making you a part of surveillance capitalism.

The Contra Chrome comic explains why this is bad, and why you should use another browser.