Netty的线程模型如图所示,可知一个EventLoopGroup中管理着多个EventLoop,Netty中的每个EventLoop都有自己的单独的线程来执行任务
下面从源码角度来分析一下EventLoopGroup是如何调度多个线程不相同的EventLoop的
以NioEventLoopGroup为例入手分析,其继承结构为
其中主体方法的实现都在MultithreadEventExecutorGroup和MultithreadEventLoopGroup类中
MultithreadEventExecutorGroup
/**
* Abstract base class for {@link EventExecutorGroup} implementations
* that handles their tasks with multiple threads atthe same time.
*/
//实现同时处理多线程任务的方法
public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup
属性
1、children 存储
EventExecutor就是EventLoop的父类,这就是EventLoop在group中的存储结构
private final EventExecutor[] children;
//构造方法中的赋值,根据线程数赋值
children = new EventExecutor[nThreads];
2、chooser 调度
private final EventExecutorChooserFactory.EventExecutorChooser chooser;
//将所有executor都交给chooser调度
chooser = chooserFactory.newChooser(children);
chooser的实现 重点是next方法的实现
private static final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser {
private final AtomicInteger idx = new AtomicInteger();
private final EventExecutor[] executors;
PowerOfTwoEventExecutorChooser(EventExecutor[] executors) {
this.executors = executors;
}
@Override
//index++的方式来遍历执行器数组
public EventExecutor next() {
return executors[idx.getAndIncrement() & executors.length - 1];
}
}
方法
1、next 轮询executor数组
public EventExecutor next() {
return chooser.next();
}
2、shutdownGracefully 关闭
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
for (EventExecutor l: children) {//轮询关闭
l.shutdownGracefully(quietPeriod, timeout, unit);
}
return terminationFuture();
}
MultithreadEventLoopGroup
方法
1、register 注册channel
public ChannelFuture register(Channel channel) {
return next().register(channel);//转移给executor来实现,最终还是转交给channel来实现
}
总结
上图转自https://blog.csdn.net/z69183787/article/details/52623699
EventLoopGroup实际上就是一个线程池,每一个EventLoop都相当于一个线程,Netty所做的就是将这个线程池有效的调度起来。