2021SC@SDUSC
文章目录
一、前言
本篇博客将会基于上一篇博客中服务端的代码,分析bossGroup和workerGroup在创建过程中,具体进行了什么操作。注意到,bossGroup和workerGroup其实都是NioEventLoopGroup类的实例。
二、NioEventLoopGroup
图片为NioEventLoopGroup的类图,有IDEA 生成,可以看见,NioEventLoopGroup其实就是线程池。在java中,推荐通过Executor来管理线程池,从而将线程池的管理与具体业务分离。
三、NioEventLoopGroup构造方法
以bossGroup的创建为例,调用了public NioEventLoopGroup(int nThreads)方法。
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
之后,一直调用到 public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,final SelectStrategyFactory selectStrategyFactory)方法。
public NioEventLoopGroup(int nThreads, Executor executor, final SelectorProvider selectorProvider,
final SelectStrategyFactory selectStrategyFactory) {
super(nThreads, executor, selectorProvider, selectStrategyFactory, RejectedExecutionHandlers.reject());
}
至此,提供了nThreads(线程数),Executor,SelectorProvider、SelectStrategyFactory、RejectedExecutionHandler。之后,调用父类MultithreadEventLoopGroup构造方法。
四、MultithreadEventLoopGroup构造方法
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
这里注意到,有一个对nThreads是否为0的判断,在NioEventLoopGroup的无参构造中,实际上调用了new NioEventLoopGroup(0)。也就是说,如果使用了NioEventLoopGroup的无参构造方法,最后的线程数量实际上等于默认值。
private static final int DEFAULT_EVENT_LOOP_THREADS;
static {
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
}
}
在MultithreadEventLoopGroup的静态代码块中,对该默认值进行了初始化,一般地,该值等于CPU核数的两倍。
五、MultithreadEventExecutorGroup构造方法
最后,对NioEventLoopGroup的具体实现在MultithreadEventExecutorGroup类中。
protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
EventExecutorChooserFactory chooserFactory, Object... args) {
checkPositive(nThreads, "nThreads");
if (executor == null) {
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
boolean success = false;
try {
children[i] = newChild(executor, args);
success = true;
} catch (Exception e) {
// TODO: Think about if this is a good exception type
throw new IllegalStateException("failed to create a child event loop", e);
} finally {
if (!success) {
for (int j = 0; j < i; j ++) {
children[j].shutdownGracefully();
}
for (int j = 0; j < i; j ++) {
EventExecutor e = children[j];
try {
while (!e.isTerminated()) {
e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
}
} catch (InterruptedException interrupted) {
// Let the caller handle the interruption.
Thread.currentThread().interrupt();
break;
}
}
}
}
}
chooser = chooserFactory.newChooser(children);
final FutureListener<Object> terminationListener = new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (terminatedChildren.incrementAndGet() == children.length) {
terminationFuture.setSuccess(null);
}
}
};
for (EventExecutor e: children) {
e.terminationFuture().addListener(terminationListener);
}
Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
Collections.addAll(childrenSet, children);
readonlyChildren = Collections.unmodifiableSet(childrenSet);
}
可以看到,在方法中,首先完成了对nThreads是否为正数的判断,接着,在之前的调用中,传入的Executor是null,这里完成了对Executor的初始化。
children是一个EventExecutor数组,实际上是EventLoop的数组,对其初始化,大小为nThreads。最后,对children中每一个EventExecutor进行初始化,方法为newChild(executors, args),newChild是一个抽象方法,具体实现有NioEventLoopGroup实现,将会在下一篇博客中分析。
如果一个EventExecutor创建失败,则将之前的EventExecutor全部关闭。
如果全部创建成功,则先有chooserFactory创建一个chooser,即轮询算法,之后为每一个EventExecutor添加一个FutureListener,最后,将children转为一个只读的集合。
六、总结
本篇博客在大体上浏览了NioEventLoopGroup创建的过程,分析了关于线程池中现成的数量是何时决定的,以及EventLoop数组的初始化。还有很多细节将会在下一篇博客中分析。