您的位置:首页 > 运维架构

Netty中NioEventLoopGroup

2018-03-29 21:56 946 查看
NioEventLoopGroup是用于NIO中基于Channel的Selector的实现。
{@link MultithreadEventLoopGroup} implementations which is used for NIO {@link Selector} based {@link Channel}s.
它本身提供了无参的构造方法 /**
* Create a new instance using the default number of threads, the default {@link ThreadFactory} and
* the {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}.
* 使用默认的线程数,线程工厂以及SelectorProvider,这个SelectorProvider通过调用SelectorProvider的provider()返回
*/
public NioEventLoopGroup() {
this(0);
}在它的父类MultithreadEventLoopGroup中会有对具体的线程数的判断 static {
//这就在静态代码块中获取计算CPU的超线程核数*2作为默认的线程数
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);
}
}

/**
* @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...)
*/
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}group中的chooser的作用就是在group中产生的EventLoop数组中,选择一个eventLoop用来注册channel的感兴趣事件
在EventLoopGroup的实现类中,存在着新建一定数量的eventloop然后保存起来的的实现 children = new EventExecutor[nThreads];

for (int i = 0; i < nThreads; i ++) {
boolean success = false;
try {
                //对他的eventloop数组进行赋值
                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);

4000
}
} catch (InterruptedException interrupted) {
// Let the caller handle the interruption.
Thread.currentThread().interrupt();
break;
}
}
}
}
}
        //作为group.next()方法的选择器。
chooser = chooserFactory.newChooser(children);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  NioEventLoopGroup