请教nio阻塞问题

RomanticProgrammer 2004-04-08 03:49:02


我的nio遇到个阻塞问题一直没解决,请教高手
我的socket server不是一问一答试,即使socket客户端无请求,server也可能主动发数据。我给每个socketchannel一个queue,上层(另一个线程)把数据enqueue后就返回。
SocketChannel注册了读事件和写事件,开始时只关注读事件,当有数据入队的时候才关注写事件,数据发完queue为空后又只关注读事件。问题就出在数据入队是另一个线程进行的,在enqueue方法中关注写事件 interestOps方法可能被阻塞。

一问一答的服务器就不会有这个问题,我可以在读事件完成后关注写事件,完全在同一个线程中进行。

想了很多办法,如果让它一直都关注读写事件的话,socketChannel上因为一般都是可写的,所以会不断有写事件触发而队列中实际没数据,while循环不断进行cpu占用率很高,如果sleep一下虽然可以解决cpu占用率的问题,但程序看起来还是很别扭,进行了很多没有意义的循环。
如果写数据根本不管它是不是isWriteable直接写,那又不能异步io了,其它线程都有可能被socket阻塞。

下面是我在O’Reilly JAVA NIO上找到的相关的一段话。

interest set are synchronized by Selector objects. This could cause calls to the interestOps( ) method to block for an indeterminate amount of time. The specific locking policy used by a selector, such as whether the locks are held throughout the selection process, is implementation-dependent. Luckily, this multiplexing capability is specifically designed to enable a single thread to manage many channels. Using selectors by multiple threads should be an issue in only the most complex of applications. Frankly, if you're sharing selectors among many threads and encountering synchronization issues, your design probably needs a rethink.

我的设计需要重想?难道nio实现socketserver端发送队列需要一个循环去轮询队列中有数据没有么?我想做到另一个线程enqueue之后,告诉它该关注写事件了。

...全文
120 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
CyberGhost 2004-04-23
  • 打赏
  • 举报
回复
如果写数据根本不管它是不是isWriteable直接写,那又不能异步io了,其它线程都有可能被socket阻塞。

能解释一下吗
我直接写不管是不是isWriteable
好像没有问题阿
panpan221 2004-04-23
  • 打赏
  • 举报
回复
新手关注一下
vongood 2004-04-23
  • 打赏
  • 举报
回复
学习学习。

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧