为什么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回答

闪电侠

2019-09-30

您好,可以看一下 github 关于为什么要添加这段代码的逻辑:https://github.com/netty/netty/issues/5566

0
1
binarylife
非常感谢!
2019-10-01
共1条回复

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,因此这里添加到线程中排除来延迟执行.


 */


0
0

Java读源码之Netty深入剖析

解析netty各大组件细节,百万级性能调优,设计模式实际运用

2334 学习 · 283 问题

查看课程