What is the best way to set a timeout to close a NIO SocketChannel if there is no data is received for a certain period after the connection is established?
2 Answers
Either:
You are using a
Selector
, in which case you have a select timeout which you can play with, and if it goes off (select(timeout)
returns zero) you close all the registered channels, orYou are using blocking mode, in which case you might think you should be able to call
Socket.setSoTimeout()
on the underlying socket (SocketChannel.socket()
), and trap theSocketTimeoutException
that is thrown when the timeout expires duringread()
, but you can't, because it isn't supported for sockets originating as channels, orYou are using non-blocking mode without a
Selector
, in which case you need to change to case (1).
So you either need to use case (1) or a java.net.Socket
directly.

- 305,947
- 44
- 307
- 483
-
I am using case 1. But as I understand, the select(timeout) is triggered if there are no channels selected at all. What I need to do is close an already connected SocketChannel if it does not send any readable data (i:e change from OP_ACCEPT to OP_READ) within a given time. Am I making sense? – Sam Jun 28 '13 at 03:40
-
1Sure but you can't do that directly in case 1. You would have to keep track of the last read time for each channel and manipulate the select timeout so that the least recently read channel's timeout will expire if nothing happens, check all channels for timeouts, etc. – user207421 Jun 28 '13 at 19:10
-
I'm sorry what did you mean by 'manipulate the select timeout'? – Sam Jul 01 '13 at 11:23
-
2As per [this previous question](http://stackoverflow.com/questions/2866557/timeout-for-socketchannel-doesnt-work) case #2 will not work. It has an answer showing how to do it though. – Matthieu Feb 08 '15 at 18:41
-
@Sam Err, change its value? – user207421 Jun 04 '20 at 11:31
I was looking for the same recommendation and could not find it easily - sharing it here.
There is a nice handler for netty called: ReadTimeoutHandler.
One can use it like that
channel.pipeline().addLast(new ReadTimeoutHandler(readTimeout));
it will drop io.netty.handler.timeout.ReadTimeoutException when failed to see any data doing the defined read timeout.

- 71
- 3