完全理解NIO Selector
一、Selector是什么
Selector是一個(gè)或多個(gè)SelectableChannel對(duì)象的多路復(fù)用器.二、如何創(chuàng)建一個(gè)Selector對(duì)象
三、如何將selectable channel注冊(cè)到selector中
SelectionKey key = channel.register(selector,Selectionkey.XXX);四、selector如何維護(hù)selection keys
一個(gè)selector維護(hù)著三個(gè)selection keys集合:
對(duì)于一個(gè)新創(chuàng)建的selector其中這三個(gè)集合都是空著的。
五、selector如何選擇就緒channel
- 每次 selection operation 期間, keys都可以添加到或從selector’s selected-key set 被移除,同時(shí)也可- 以從它的 key 和 cancelled-key sets 被移除。 selection operation 可以被觸發(fā)通過(guò)執(zhí)行selector.select(),selector.select(long),和selector.selectNow() 方法,并且這些方法涉及到以下三個(gè)步驟:
首先每個(gè)位于 cancelled-key set
中的key會(huì)從每個(gè)包含它的key集合中被移除,并且對(duì)應(yīng)的channel會(huì)被撤銷(xiāo)登記。這個(gè)步驟使得 cancelled-key set
變?yōu)榭铡?/p>
查詢底層操作系統(tǒng)來(lái)獲得關(guān)于selector中剩余channel的就續(xù)事件從 selection operation
開(kāi)始截止到此刻的更新情況,只要哪個(gè)channel的就續(xù)事件的更新部分有至少一個(gè)與興趣集中的操作匹配上,那么將會(huì)執(zhí)行以下兩個(gè)動(dòng)作:
那么將它添加到這個(gè)集合中,并將它的就緒操作集(ready-operation set)修改成
只包含使得channel被報(bào)告就緒的操作,任何先前記錄在就緒操作集中的就緒信息都會(huì)被丟棄。
使得channel被報(bào)告就緒的操作 寫(xiě)入進(jìn)去;總而言之,系統(tǒng)底層會(huì)通過(guò)按位與&操作更新當(dāng)前就緒集。
sets)都不會(huì)被更新。
- selection operations 是否會(huì)阻塞等待一個(gè)或多個(gè)通道準(zhǔn)備就緒,以及等待多長(zhǎng)時(shí)間,這是三種選擇方法之間唯一的本質(zhì)區(qū)別。
六、selector線程安全嗎
多線程并發(fā)情況下Selectors本身是線程安全的,但是他們所持有的key sets不是線程安全的。
selection operations 按順序在selector本身,key set 和 selected-key set 上同步。 它們還在上面的步驟(1)和(3)期間在 canceled-key set 上同步。
在 selection operations 期間改變key的興趣集,對(duì)于本次操作將不會(huì)產(chǎn)生任何影響;它們的影響將會(huì)在下次 selection operations 期間發(fā)生。
selectionKey可能會(huì)被取消,channel可能隨時(shí)關(guān)閉。 因此,在一個(gè)或多個(gè)選擇器的key集中存在并不意味著selectionKey有效或其channel是開(kāi)放的。有可能另一個(gè)線程取消selectionKey或關(guān)閉一個(gè)channel,應(yīng)用程序代碼應(yīng)該小心地同步并檢查這些條件。
一個(gè)線程通過(guò)selector.select()或selector.select(long)方法產(chǎn)生的阻塞可以被其他線程用以下三種方式的任意一種來(lái)中斷:
By invoking the selector’s wakeup() method,
By invoking the selector’s close() method, or
By invoking the blocked thread’s interrupt() method, in which case itsinterrupt status will be set and the selector’s wakeup() method will
be invoked.
selector.close() 在 selection operations 期間會(huì)順序的同步selectorand all three key sets 。
一個(gè)selector的 key set 和 selected-key set 通常情況下是線程不安全的。如果一個(gè)線程想要修改這個(gè)集合,需要同步控制它。通過(guò)key集合的iterator()方法返回的Iterators提供了快速失敗(fail-fast):如果在創(chuàng)建迭代器之后修改了set,除了通過(guò)調(diào)用迭代器自己的remove() 方法之外,將拋出ConcurrentModificationException 。
文章轉(zhuǎn)自
總結(jié)
以上是生活随笔為你收集整理的完全理解NIO Selector的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 都是写需求,高手和菜鸟为何差别这么大?
- 下一篇: 线下实战-8月24号上海