Windows NIO bug?

Alan Bateman Alan.Bateman at
Fri Jul 6 17:54:40 UTC 2018

On 06/07/2018 18:06, Simone Bordet wrote:
> :
> It was my understanding that calling close() implicitly deregistered
> the socket from all selectors.
> Is that not the case, so I have to manually cancel() the correspondent
> SelectionKey?
Closing a socket channel will cancel the key but it needs a selection 
operation to remove the cancelled key from the Selector. All the details 
on this are in the Selector's javadoc.

> :
> The client does read the FIN from the server.
Right, this is because SocketChannel close will shutdown the connection 
for reading, a "half close" in TCP speak.

> :
> What I expect is a TCP RST that the server sends to the client to
> inform the client that the socket is closed on the server and that
> further writes are pointless, and that RST is not emitted by the
> server.
> On Linux it is always emitted, on Windows it is only emitted if I wake
> up the selector.
There has historically been a problematic area with both reliability 
issues and platform specific behavior. It has been re-implemented in JDK 
11 so it is now reliable and also consistent on all platforms. When you 
try JDK 11 then you should see the connection will consistently remain 
open until the keys have been removed from all Selectors. If there are 
clients reading they will read EOF. If there are clients writing then 
they will not see the RST until the key has been flushed from all Selectors.

> Note that "wake up the selector" just means selector.wakeup(), nothing
> is selected (at this point there are no keys since the only socket has
> been closed), and we go back to select().
> However, that seems enough to tell the Windows TCP stack to emit the RST.
The selection removes cancelled keys at the start and end of each 
selection. The removal from the last Selector is what triggers the final 

> That seems an inconsistent behavior, which I can certainly workaround
> (by waking up the selector), but looks like a hack.
It's the right way to do it, otherwise you will have cancelled keys 
waiting indefinitely to be de-registered.


More information about the nio-dev mailing list