Sending multiple messages through only one SocketChannel

倖福魔咒の 提交于 2019-12-02 04:45:33

You've started from the wrong place. There are numerous problems with that article. All that pending-change-queue stuff is an immense, unnecessary complication. Just wakeup() the selector if you need to register/deregister from another thread (although why you would need to do that at all is a complete mystery to me), and you can change interestOps any time the same way with perfect reliability, even if the FUD he is spreading about different implementations ever comes true.

The article has several other issues which show that the author doesn't really know what he's talking about. An IOException doesn't necessarily mean 'the remote forcibly closed the connection'. His finishConnection() method ignores the return value which, if false, means the connection is still pending, so it registers the channel beyond the OP_CONNECT stage prematurely. Closing a channel cancels the key, so all those cancel() calls that immediately precede or follow close() calls are redundant and can be removed (although there are places where he cancels without closing, which is also wrong where it occurs).

Further:

nowhere in the two methods just introduced do we request that the OP_CONNECT flag be set on the socket channel's selection key. If we did that we'd overwrite the OP_CONNECT flag and never complete the connection. And if we combined them then we'd run the risk of trying to write on an unconnected channel (or at least having to deal with that case)"

This is just complete Grade A nonsense. Setting OP_CONNECT twice, or 'combining them then', whatever that means, cannot possibly cause you to 'never complete the connection' or 'try to write on an unconnected channel'. He seems to think that setting a bit twice clears it.

Data has already been queued (or we wouldn't be establishing a connection in the first place).

A strange and unexplained assumption.

Instead of that pretty dubious mess, I would have a good look at the 'Taming the NIO Circus' thread he cites, if you can still find it after the Oracle forum migration. Disclaimer: I wrote some of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!