Handling network timeouts
When an application is deployed in the real world, new network problems can occur that were not present when this application was developed on a LAN. Problems, such as network congestion, slow connections, and the loss of a network link can result in delays or loss of messages. It is important to detect and handle network timeouts.
There are several socket options which provide some control over socket communications. The SO_TIMEOUT
option is used to set a timeout for read operations. If the specified amount of time elapses, then a SocketTimeoutException
exception is thrown.
In the following statement, the socket will expire after three seconds have elapsed:
Socket socket = new ... socket.setSoTimeout(3000);
The option must be set before a blocking read operation occurs. A timeout of zero will never time out. Handling timeouts is an important design consideration.