Channel中的executor赋值逻辑

服务端channel的executor赋值

ChannelFuture regFuture = config().group().register(channel);
    @Override
    public ChannelFuture register(Channel channel) {
        //获取EventLoop.SingleThreadEventLoop来注册.MultithreadEventExecutorGroup.next.
        EventLoop next = next();
        //eventloop和channel注册.
        return next.register(channel);
    }
    @Override
    public ChannelFuture register(final ChannelPromise promise) {
        ObjectUtil.checkNotNull(promise, "promise");
        //unsafe注册.获取channel获取unsafe在注册.
        Channel.Unsafe unsafe = promise.channel().unsafe();
        //连接和read的unsafe有什么不同.那么秘密是不是都在channel里呢?
        unsafe.register(this, promise);
        return promise;
    }

核心代码: AbstractChannel.this.eventLoop = eventLoop;(NioEventLoop)

        @Override
        public final void register(EventLoop eventLoop, final ChannelPromise promise) {
            ObjectUtil.checkNotNull(eventLoop, "eventLoop");
            //是不是已经注册过了.
            if (isRegistered()) {
                promise.setFailure(new IllegalStateException("registered to an event loop already"));
                return;
            }
            //兼容:Return true if the given EventLoop is compatible with this instance.
            if (!isCompatible(eventLoop)) {
                promise.setFailure(
                        new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
                return;
            }
            //eventLoop注册给抽象类的实例.eventLoop绑定给channel.
            AbstractChannel.this.eventLoop = eventLoop;

            //
            if (eventLoop.inEventLoop()) {
                register0(promise);
            } else {
                //main方法或者其他
                try {
                    //这里开始第一次启动线程.注册注册事件.main线程.
                    eventLoop.execute(new Runnable() {
                        @Override
                        public void run() {
                            register0(promise);
                        }
                    });
                } catch (Throwable t) {
                    logger.warn(
                            "Force-closing a channel whose registration task was not accepted by an event loop: {}",
                            AbstractChannel.this, t);
                    closeForcibly();
                    closeFuture.setClosed();
                    safeSetFailure(promise, t);
                }
            }
        }

ChannelHandlerContext里的executor是如何赋值的

so easy.

   @Override
    public EventExecutor executor() {
        //如果为空,冲channel里获取.
        if (executor == null) {
            return channel().eventLoop();
        } else {
            return executor;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容