前言數組
本文將分析EventLoopGroup初始化、EventLoop的選擇策略以及Channel是如何經過EventLoop註冊到Selector上的。 微信
1、EventLoopGroup類圖概覽多線程
在客戶端示例代碼中的中實例化了NioEventLoopGroup,接下來分析下該實例化過程。 app
EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workerGroup);
從如下類圖結構io.netty.util.concurrent.AbstractEventExecutorGroup分支主要負責多線程任務的處理;io.netty.channel.EventLoopGroup分支主要負責Channel相關的註冊。MultithreadEventExecutorGroup與MultithreadEventLoopGroup分別繼承和實現了上面AbstractEventExecutorGroup和EventLoopGroup,將其負責的功能進行融合。框架
2、構造函數解讀編輯器
構造函數
nThreads:eventLoopThreads線程數量,默認值0時取CPU核數的2倍,能夠經過參數io.netty.eventLoopThreads指定
Executor:默認ThreadPerTaskExecutor
SelectorProvider默認SelectorProvider.provider(),用於開啓Selector和Channel
SelectStrategyFactory:SelectStrategy工廠類,默認DefaultSelectStrategyFactory
EventExecutorChooserFactory:EventExecutor選擇器,默認爲DefaultEventExecutorChooserFactoryide
3、初始化EventExecutor數組函數
代碼解讀
EventExecutor[] children:數組大小爲nThreads,默認爲CPU核數乘以2。
EventExecutor繼承了EventExecutorGroup本質上爲線程框架類Executor
children[i]:數據元素爲EventLoop,本示例中爲NioEventLoop。oop
NioEventLoop類圖
NioEventLoop繼承了SingleThreadEventLoop,SingleThreadEventLoop同時繼承和實現了EventExecutor和EventLoop。即:NioEventLoop擁有了線程類框架處理多線程任務的能力和處理Channel能力。學習
備註:本文中EventExecutor數組children的元素爲NioEventLoop,NioEventLoop同時擁有線程框架能力和Channel註冊等處理能力。
4、EventExecutor選擇器
第三部分對EventExecutor[] children進行初始化分析,然在使用時如何選擇其中一個元素呢?
在初始化過程當中有如下一行代碼,用於初始化EventExecutorChooser。
chooser = chooserFactory.newChooser(children);
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
@2 若是數組長度不是2的冪次方,選擇GenericEventExecutorChooser,executors[Math.abs(idx.getAndIncrement() % executors.length)]。
5、Channel註冊
Channel註冊入口
選擇EventLoop
本文爲NioEventLoop
綁定Channel到EventExecutor
經過DefaultChannelPromise綁定Channel到EventExecutor(NioEventLoop)
將Channel註冊到Selector
做者丨梁勇
來源丨瓜農老梁(ID:gh_01130ae30a83)
歡迎關注公衆號「瓜農老梁」
本文分享自微信公衆號 - 瓜農老梁(gh_01130ae30a83)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。