Java socket timeout: How to set the timeout on a Java socket

Java socket FAQ: How do I set the timeout value on a Java socket? That is, when I’m trying to read data from a Java socket, and I’m not getting any response from the server, how do I make sure my code doesn’t get stuck at this point? (It needs to time out after several seconds.)

Solution: Java socket timeout

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code:

String serverName = "localhost";
int port = 8080;

// set the socket SO timeout to 10 seconds
Socket socket = openSocket(serverName, port);
socket.setSoTimeout(10*1000);

Here’s a quote from the Socket class Javadoc, specifically the Javadoc for this setSoTimeout method:

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.

If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect.

The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Setting the Java socket timeout in milliseconds

As shown in the example Java code above, whenever I deal with calls like this socket timeout setting that involve milliseconds, I write my code this way:

socket.setSoTimeout(10*1000);

Some programmers give me grief about this, but I think it shows my intent, and it’s also easier for humans to read 10*1000 than it is something like 10000 or 100000.