问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/28754275/selector-wakeup-and-happens-before-relationship