我们都知道Netty的线程模型是基于React的线程模型,并且我们都知道Netty是一个高性能的NIO框架,那么其线程模型必定是它的重要贡献之一。
在使用netty的服务端引导类ServerBootstrap或客户端引导类Bootstrap进行开发时,都需要通过group属性指定EventLoopGroup, 因为是开发NIO程序,所以我们选择NioEventLoopGroup。
接下来的两篇文章,我将从源码角度为大家深入浅出的剖析Netty的React线程模型工作机制。
本篇侧重点是NioEventLoopGroup。
首先我们先回顾一下,服务端初始化程序代码(省略非相关代码):
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
... // 已省略非相关代码
// 侦听8000端口
ChannelFuture f = b.bind(8000).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
在分析源码之前,我们先看看NioEventLoopGroup的类继承结构图:
初始化bossGroup及workerGroup时,使用了NioEventLoopGroup的无参构造方法,本篇将从此无参构造入手,详细分析NioEventLoopGroup的初始化过程。
首先我们看看NioEventLoopGroup的无参构造方法:
public NioEventLoopGroup() {
this(0);
}
其内部继续调用器构造方法,并指定线程数为0:
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
继续调用另一个构造方法,指定线程为0,且Executor为null:
public NioEventLoopGroup(int nThreads, Executor executor) {
this(nThreads, executor, SelectorProvider.provider());
}
在此构造中,它会指定selector的辅助类 “SelectorProvider.provider()”,我们继续查看它的调用:
public NioEventLoopGroup(
int nThreads, Executor executor, final SelectorProvider selectorProvider) {
this(nThreads, executor, selectorProvider, Defaul