java selector wakeup,Selector.wakeup()和“在发生之前”关系

Im writing yet another NIO server. There is a selector thread that performs reading, processing (for the most cases) and writing (pseudo-code below, not real Java):

while (true) {

select();

for (key : keys) {

if (isReading(key)) {

data = read(key.channel());

result = process(data);

key.interestOps(OP_WRITE);

}

if (isWriting(key)) {

key.channel().write(result);

}

}

}

The processing for the most cases is trivial, so should be fine. However there are (rare) cases, when processing is time-consuming and should be delegated to another thread. Therefore, that thread should somehow tell selector to be interested in OP_WRITE as the processing is done.

As I see there are at least 2 approaches to do:

Calling wakeup() and register() for a write in the same (worker) thread using synchronization to prevent next select() from happening not to cause register() to hang.

Enqueueing a "register" operation then calling wakeup() in the worker thread to allow selector thread dequeue the operation to register for writing in the same thread.

My question is: do I have to use a thread-safe queue implementation (say, ConcurrentLinkedQueue) if I choose method #2? I suspect I dont since enqueue() "happens-before" dequeue() which is guaranteed by wakeup() call, but I cant formally prove it.

Please help! Thanks!

解决方案

As per my comment, your question is founded on a fallacy. You don't need to 'tell the selector to be interested in OP_WRITE as the processing is done'. You just write the response when you've created it. Only in the case where that write returns zero does it become necessary to interest the selector in OP_WRITE for the channel.

To answer your supplementary question, select() engages in three documented levels of synchronization. wakeup() doesn't, but you would normally follow wakeup() wih a block synchronized on the selector, inside which you would play with whatever the selector needs to know about next time it selects. This accomplishes all the necessary happens-before relationships.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值