Netty进阶学习(六):Netty#initAndRegister#register()理解
背景
- 究竟是哪个线程执行了doRegister()方法?
- Channel实例是谁?
- Selector实例是谁?又怎么绑定到NioEventLoop上的?
过程
- EventLoop执行register0()#doRegister()方法
启动的时候是main主线程,并不是EventLoop线程。然后new一个任务的方式丢到EventLoop中,它是放到队列中的,然后启动线程。这个时候才会去 Queue中拿到task并且执行。然后执行我们的doRegister()方法的。 javaChannel().register(eventLoop().unwrappedSelector(), 0, this),这里的this非常重要,是Attachment类型。实际传递的是NioServerSocketChannel实例。
javaChannel()是当前channel(实际上是JDK的SelectableChannel的实例),eventLoop实例中有Selector(JDK中的Selector)的引用,带来的attachment内容就是NioServerSocketChannel实例,当事件发生的时候,需要对事件进行处理,这个时候需要拿到NioServerSocketChannel。NioEventLoop上会绑定一个Selector,是怎么绑定的?这个NioEventLoop类就持有NIO相关组件如Selector和SelectedSelectionKeySet。创建NioEventLoopGroup实例的时候,底层代码就会创建Selector实例,并赋值给NioEventLoop实例的Selector属性。
小结
- 因为注册过程是NIO底层的执行逻辑。
- 辅助阅读。
Java NIO的Selector核心类图及其执行逻辑分析
Java NIO的Selector、Channel、Buffer相互之间的关系
还没有评论,来说两句吧...