类结构图
NioEventLoopGroup
MultithreadEventLoopGroup NioEventLoopGroup MultithreadEventExecutorGroup AbstractEventExecutorGroup <<interface>> EventExecutorGroup <<interface>> EventLoopGroup
NioEventLoop
<<interface>> EventExecutor AbstractEventExecutor AbstractScheduledEventExecutor SingleThreadEventExecutor SingleThreadEventLoop NioEventLoop <<interface>> EventLoop
初始化
线程池创建是通过MultithreadEventExecutorGroup
构造函数,创建线程是通过DefaultThreadFactory
首先创建EventExecutor的数组
cpp
children = new EventExecutor[nThreads];
NioEventLoopGroup的newChild
创建具体的eventloop即NioEventLoop
SingleThreadEventExecutor在重写了线程池的execute方法时,其会创建线程,执行SingleThreadEventExecutor.this.run()
抽象方法
同时会初始化EventExecutorChooser
, 有两种类型
- PowerOfTwoEventExecutorChooser
- GenericEventExecutorChooser
初始化SelectorProvider,默认使用sun.nio.ch.DefaultSelectorProvider.create()
java
public static SelectorProvider provider() {
synchronized (lock) {
if (provider != null)
return provider;
return AccessController.doPrivileged(
new PrivilegedAction<SelectorProvider>() {
public SelectorProvider run() {
if (loadProviderFromProperty())
return provider;
if (loadProviderAsService())
return provider;
provider = sun.nio.ch.DefaultSelectorProvider.create();
return provider;
}
});
}
}
初始化DefaultSelectStrategy,默认使用SelectStrategy.SELECT
创建NioEventLoop传递的executor参数为ThreadPerTaskExecutor