请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

为什么Netty服务端启动时ServerBootstrapAcceptor的添加要放到线程中?

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

0 回复 有任何疑惑可以回复我~
  • 提问者 binarylife #1
    非常感谢!
    回复 有任何疑惑可以回复我~ 2019-10-01 22:07:19
提问者 binarylife 2019-10-01 22:08:34

// 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 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信