jQuery in Action, 2nd edition
The moose likes Java in General and the fly likes clarification needed on setSoTimeout() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "clarification needed on setSoTimeout() " Watch "clarification needed on setSoTimeout() " New topic

clarification needed on setSoTimeout()

jaibhim max

Joined: Nov 15, 2010
Posts: 21
Hi All,

I am opening one channel and reading some streams through a socket. If i use setSoTimeout(5000), it is expected that socket will be closed after 5 seconds.
Consider, I have established SSH connection with a server and reading data through socket, I want to know -
1. If my operation through that socket is taking 20 seconds, will that socket will be timed out after 5 seconds even if the operation is in progress?
2. If my connection breaks with the server when it is reading data through that socket, will my socket be timed out after 5 seconds?

Akash Mahakode
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14601

jaibhim max wrote:If i use setSoTimeout(5000), it is expected that socket will be closed after 5 seconds.

So, what exactly do you expect: if you call this, then after 5 seconds the socket connection is automatically closed?

That's not what setSoTimeout does. In fact, it does not have anything to do with closing the socket. The API documentation describes it in detail:
Socket.setSoTimeout wrote: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.

In other words: if you call read() on the socket's input stream and nothing is received within 5 seconds, you will get a SocketTimeoutException. That doesn't mean that the connection is closed; it only means that no data was received on the socket within 5 seconds. The connection will still be open if you get the exception.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
rocket mass heater kickstarter
subject: clarification needed on setSoTimeout()