views:

171

answers:

2

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?

A: 

Your solution of using a Timer is the way that I would probably go about doing it.

An alternative solution would be to validate every connection each time that select returns. You could use the select method that takes a timeout parameter and tailor that timeout to something suitable for your requirements. This would involve maintaining information about when each connection last received data.

Matthew T. Staebler
+1  A: 

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.

Brian Roach