views:

765

answers:

3

From the JavaDoc for setSoTimeout

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.

From the variety of posts on the Internet I have read that SO_TIMEOUT is rather unreliable when using Socket C API ( e.g. here ).

Hence the question, is it reliable to use setSoTimeout to check for run-away sessions?

If not, what techniques can you recommend to put a time limit on socket sessions?

A: 

Check out the connectivity classes in Java 6 nio, they include sockets now and do non-blocking operation so you can cancel an operation if you want to.

Apache htmlclient core (?) is now able to use the nio sockets, so it seems they got that concept working. That's all I know about it, though.

Carl Smotricz
But whether nio sockets would work properly on an OS with a broken network stack is anyone's guess ...
Stephen C
Not only can you cancel an nio operation, but Selector.select(long timeout) should work too.
Seth
Can you guarantee that? On a machine with a **broken** network stack? I would say that you can't because you cannot assume that the syscall that implements select will work correctly for a socket.
Stephen C
+2  A: 

I don't know any relevant recent/current operating system, on which (stream) socket timeouts are not working as they are supposed to. The post you're linking to is from a rather confused poster, which is trying to set a send timeout on a datagram socket, which makes absolutely no sense. Datagrams are either sent immediately or silently discarded.

jarnbjo
+1 - The linked post is indeed extremely confused. In addition to the timeout on UDP nonsense, he seems to think that you should be able to send arbitrarily large UDP datagrams.
Stephen C
+1  A: 

I am not aware of any modern platform OS platform whose network stack is so broken that socket timeouts don't work. But if anyone knows of a real life example, please add it as a comment!

I would not worry about this scenario unless you are actually forced to support your application on such a broken OS. I suspect that it would be a painful exercise.

Stephen C