本文是对Netty中NioEventLoopGroup的简单分析,该类是连接接入的入口,它负责新连接的接入与连接事件的处理,接下来我会从使用它的角度去分析该类的作用,通过本文你将了解到Netty是如何创建线程去处理连接的,如果文章中有错误希望能够指出,谢谢。
NioEventLoopGroup之大管家
- 我们在编写Netty服务的时候,首先会创建bossGroup与workerGroup,如下:
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
- 接下来我们一步步分析该类作了什么事情,bossGroup与workerGroup初始化类似,这里从bossGroup的创建开始分析。
首先通过构造函数将线程数传递进去,这个线程数是用来处理新连接的线程数量,之后创建一个空的线程池Executor。接下来会分析创建bossGroup 的主线,其它边边角角不会做过多的分析。
1.执行构造方法
# 传入线程数nThreads与一个空的线程池对象
public NioEventLoopGroup(int nThreads) {
this(nThreads, (Executor) null);
}
2.MultithreadEventLoopGroup类中的方法
# 这里可以看到做了个判断,如果输入了nThreads ,就默认输入值
# 如果没有输入,那么创建系统的默认值DEFAULT_EVENT_LOOP_THREADS ,默认大小为CPU核数的二倍
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
3.ThreadPerTaskExecutor
# ThreadPerTaskExecutor这个类很重要,它实现了Executor,可以看作是一个线程池,bossGroup中就是一个线程的线程池
protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
this(nThreads, threadFactory == null ? null : new ThreadPerTaskExecutor(threadFactory), args);
}
4.MultithreadEventExecutorGroup类中的方法,核心方法
protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
EventExecutorChooserFactory chooserFactory, Object... args) {
if (nThreads <= 0) {
throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
}
# 这里可以看到,创建了ThreadPerTaskExecutor线程池对象
# newDefaultThreadFactory()创建默认线程工程,该方法里面创建了线程池的名称nioEventLoopGroup-x-xx这种形式
# x与xx代表第几个线程组和第几个线程
if (executor == null) {
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
boolean success = false;
try {
# newChild(executor, args)会在底层创建一个NioEventLoop线程,并将线程执行器executor保存
# 还保存了一个MpscQueue任务队列与绑定了selector选择器
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;
}
}
}
}
}
# 这里是根据一定的算法取出一个NioEventLoop线程
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);
}
5.children[i] = newChild(executor, args)
# NioEventLoopGroup类中的方法,这里可以看到创建了一个NioEventLoop线程
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
return new NioEventLoop(this, executor, (SelectorProvider) args[0],
((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
}
# 创建NioEventLoop线程的具体实现
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
# 这个super方法里面实际上创建了一个任务队列,用来异步执行非IO型任务
super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
if (selectorProvider == null) {
throw new NullPointerException("selectorProvider");
}
if (strategy == null) {
throw new NullPointerException("selectStrategy");
}
provider = selectorProvider;
final SelectorTuple selectorTuple = openSelector();
# 创建了selector连接器对象,保存到了NioEventLoop中
selector = selectorTuple.selector;
unwrappedSelector = selectorTuple.unwrappedSelector;
selectStrategy = strategy;
}
-
从上面分析可以得到下图关系,一个bossGroup中包含了一个NioEventLoop线程对象,NioEventLoop中包含了selector和任务队列
-
根据bossGroup的分析,可以得到workerGroup对象中的结构,如下图: