by

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.

Write a Comment

Comment

  1. 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.

  2. 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.

  3. 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!!