为什么Netty服务端启动时ServerBootstrapAcceptor的添加要放到线程中?
来源:5-5 新连接NioEventLoop的分配和selector注册

binarylife
2019-09-24
ServerBootstrap的init()方法中,有这样一段逻辑:
if (handler != null) {
pipeline.addLast(handler);
}
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
为什么对ServerBootstrapAcceptor的添加,要放到线程中执行,而不是直接同步添加?
2回答
-
您好,可以看一下 github 关于为什么要添加这段代码的逻辑:https://github.com/netty/netty/issues/5566
012019-10-01 -
binarylife
提问者
2019-10-01
// See https://github.com/netty/netty/pull/5576 and https://github.com/netty/netty/issues/5566
/*
* Motivation:
* When a ChannelInitializer is used via ServerBootstrap.handler(...) the users handlers may be added after the internal ServerBootstrapAcceptor. This should not happen.
* Modifications:
* Delay the adding of the ServerBootstrapAcceptor until the initChannel(....) method returns.
*
* 为什么这里必须再包一层线程,而不能直接pipeline.addLast?
* 因为如果上面的handler为ChannelInitializer,而ChannelInitializer内部执行了pipeline.addLast,那么该操作可能会在ServerBootstrapAcceptor执行.
* 为了确保所有用户Handler都在ServerBootstrapAcceptor之前添加到pipeline,因此这里添加到线程中排除来延迟执行.
*/
00
相似问题