java selector wakeup_java – 如何检测Selector.wakeup调用
我猜想根據(jù)Selector#select()和Selector#selectedKeys()的合同,原則上提議的片段根本不起作用.從
Selector開始:
The selected-key set is the set of keys such that each key’s channel was detected to be ready for at least one of the operations identified in the key’s interest set during a prior selection operation. This set is returned by the selectedKeys method.
public abstract int select(long timeout)
throws IOException
Returns:
The number of keys, possibly zero, whose ready-operation sets were
updated
當(dāng)我讀到它時(shí),selectedKeys集的大小應(yīng)始終等于select by definition返回的數(shù)字.我注意到 – 你可能也有 – 一些實(shí)現(xiàn)并不完全遵循文檔,事實(shí)上selectedKey返回所有具有更新的就緒操作集的鍵,即使它們?cè)谡{(diào)用select期間沒有更新.由于呼叫喚醒而選擇喚醒的唯一其他指示符可能是鍵的數(shù)量為零;但是,任何一種方法充其量都是不可靠的.
正如通過并發(fā)控制所暗示的那樣,處理此問題的常用方法.我不擔(dān)心這里的執(zhí)行時(shí)間;這是premature optimization的經(jīng)典例子.
除非您真的擔(dān)心單位數(shù)微秒容差,否則您不會(huì)注意到任何減速 – 如果您擔(dān)心這種容差水平,那么選擇器對(duì)您來(lái)說(shuō)不夠可靠.
以下是通常機(jī)制的一個(gè)示例,使用ReentrantLock來(lái)實(shí)現(xiàn)適當(dāng)?shù)牟l(fā):
ReentrantLock selectorGuard;
Selector selector;
private void doSelect() {
// Don't enter a select if another thread is in a critical block
selectorGuard.lock();
selectorGuard.unlock();
selector.select();
Iterator keyIter = selector.selectedKeys().iterator();
while(keyIter.hasNext()) {
SelectionKey key = keyIter.next();
keyIter.remove();
// Process key
}
}
private void addToSelector() {
// Lock the selector guard to prevent another select until complete
selectorGuard.lock();
try {
selector.wakeup();
// Do logic that registers channel with selector appropriately
} finally {
selectorGuard.unlock();
}
}
總結(jié)
以上是生活随笔為你收集整理的java selector wakeup_java – 如何检测Selector.wakeup调用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 引导页源码 - 彩虹云任务引导页模板 |
- 下一篇: java-net-php-python-
