How do I handle timeouts in my networking applications?

Tim Rohaly

A timeout in a network application happens when a reply isn't received in a timely manner. Timeouts usually need to be handled in an application-specific manner because there is no "right" thing to do in the case of a timeout, and a "timely" response depends on what your expectation is in the first place.

As an example, if you're trying reach a web site using your browser, how long should you wait for the page to show up? If you can tell data is being transfered, you might wait longer than if your browser couldn't reach the site at all. What do you do if you can't reach the site? If you really need to get there, you might try many times over an extended period. If you were attempting just out of curiosity, you might just give up and never try again.

Java provides a mechanism in the Socket class which allows you to set a timeout period on a per-socket basis. By invoking the setSoTimeout(int) method before you attempt a read() operation on the socket, for example, you may specify how long, in milliseconds, the socket should wait before the read throws a java.io.InterruptedIOException. A value of zero means wait forever.