Deregister a key immediately?

Wang Weijun weijun.wang at oracle.com
Fri Jun 13 10:07:46 UTC 2014


On Jun 13, 2014, at 17:25, Alan Bateman <Alan.Bateman at oracle.com> wrote:

> On 13/06/2014 10:07, Wang Weijun wrote:
>> Hi
>> 
>> I am using NIO Selector to monitor several channels. Whenever an exception is thrown on one channel I call key.cancel(). At the beginning of the loop I also call selector.keys.isEmpty() to see if there are channels still working. However, it seems key.cancel() does not automatically remove it from selector.keys() so I add a dummy selector.select(1) after the cancel call. Until now I didn't find it harmful but is there another way to deregister the key without calling select()?
>> 
> No, you have to select (or selectNow) in order to flush the key.
> 
> I don't I understand your comment about using isEmpty "to see if there are channels still working", maybe you could expand on that.

Some channels are connecting (OP_CONNECT) some are reading (OP_READ). If all of them already fails (exception thrown) I don't need to wait anymore.

> Also when you say you get an exception then if this is an IOException (connection reset for example) then I would think the best thing is to just close the channel. The Selector will clean-up on the next select.

OK I can close it, but it could throw an exception and I'm not sure the next select() will automatically deregister it. I'll call both for safety.

Anyway, if I understand correctly, if I call selectNow() and do not touch the selectedKeys(), it won't have any affect on the next select() call, right? The next select() will still return the same value and selectedKeys() are the same since I haven't remove any of them.

Thanks
Max

> 
> -Alan.



More information about the nio-dev mailing list