Search code examples
javasocketstimeoutselectornio

Any way to get read timeouts with Java NIO/selectors?


I'm converting a Java server application which used blocking IO and thread-per-client to NIO and a single IO thread (probably a thread pool after I get the basic implementation done). The one thing I am having an issue with is disconnecting clients after they have been idle for a period.

I had previously been using SO_TIMEOUT and blocking reads. However, with selector-based IO, reads don't block... I was hoping that I'd be able to set a timeout and be able to select on read timeout, with something like SelectionKey.isReadTimeout(), but nothing like that seems to exist.

The current best solution I have come up with is to have a Timer with a TimerTask for each channel which is waiting on read, and then canceling and re-scheduling whenever a read occurs. Is there a better solution?


Solution

  • I was just looking at how I handled that in a piece of code I wrote about a year ago. It was my first time playing with the nio stuff (and actually last ... I've been away from Java since). I don't know if this is the perfect solution BUT ...

    Any time that I read data from a socket, I store the current time in an object stored in SelectionKey.attachment(). Periodically I iterate through the SelectionKeys, check the time, and disco any that have been idle past a certain time.