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