init()方法里为什么要通过新开线程的方式添加ServerBootstrapAcceptor

来源:3-3 服务端Channel的初始化

ice_wolf

2020-03-06

老师您好,问题如标题所示,虽然这段代码上有说明,但是我看得一知半解,它这么做的目的好像是为了确保用户自定义的handler在pipline中的位置比ServerBootstrapAcceptor靠前,但是这一点是怎么保证的呢?

 // We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.
                // In this case the initChannel(...) method will only be called after this method returns. Because
                // of this we need to ensure we add our handler in a delayed fashion so all the users handler are
                // placed in front of the ServerBootstrapAcceptor.
   ch.eventLoop().execute(new Runnable() {
       @Override
       public void run() {
           pipeline.addLast(new ServerBootstrapAcceptor(
                   currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
       }
   });
写回答

1回答

闪电侠

2020-03-07

因为调用这个方法的线程是用户的线程,如果想要确保用户自定义 handler 都在 ServerBootstrapAcceptor 前面完成,只需要在同步的线程中去完成即可,然后 ServerBootstrapAcceptor 在 reactor 线程中执行,而在 reactor 线程中执行的时间肯定是要比本次同步执行的时机要晚,所以能够保证

1
2
慕妹9150414
回复
ice_wolf
同步线程指的是现在调用ch.eventLoop().execute()的这个线程而reactor线程是指去执行添加ServerBootstrapAcceptor的那个线程吗? 是的。 如果是的话为什么reactor 线程中执行的时间肯定是要比本次同步执行的时机要晚呢? 因为在下面的代码里, if (handler != null) 这个语句是先执行的 ``` p.addLast(new ChannelHandler[]{new ChannelInitializer() { public void initChannel(Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); ChannelHandler handler = ServerBootstrap.this.config.handler(); if (handler != null) { pipeline.addLast(new ChannelHandler[]{handler}); } ch.eventLoop().execute(new Runnable() { public void run() { pipeline.addLast(new ChannelHandler[]{new ServerBootstrap.ServerBootstrapAcceptor(currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)}); } }); } }}); ```
2021-03-27
共2条回复

Java读源码之Netty深入剖析

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

2334 学习 · 283 问题

查看课程