Search code examples
javaniosocketchannel

Detecting when ServerSocketChannel closes when in selector.select()


When i have a selector.select() registered to a SocketChannel, and i close the SocketChannel's peer in a separate thread, selector.select() returns, and that channel's READ operation is set. If i have a ServerSocketChannel registered to the selector, and i close the ServerSocketChannel, selector.select() does not return. Is there anyway i can detect that the ServerSocketChannel was closed while being blocked in selector.select()?

I tried using selector.wakeup(), and going through the set of keys (not selected keys), and seeing if there are any unopened channels in the set, but as soon as the close is done on the ServerSocketChannel, it is deregistered from selector, so it is not in the select.keys() set.


Solution

  • Is there anyway i can detect that the ServerSocketChannel was closed while being blocked in selector.select()?

    If you want selector.select() returns so you can extract the closed channel in selected keys then no. As docs says

    It returns only after at least one channel is selected, this selector's wakeup method is invoked, or the current thread is interrupted, whichever comes first.

    Since there is no such interest op like OP_CLOSE the only way to make select method return on channel close is to wakeup explicitly. But the key is implicitly cancelled.

    Anyway, it not that much you can do with a closed channel.

    Also EPollSelectorProvider is proxying calls to the underlying epoll and it does not have an event like you want either. http://man7.org/linux/man-pages/man2/epoll_ctl.2.html