美文网首页
Netty笔记-Channel和EventLoop

Netty笔记-Channel和EventLoop

作者: 兴浩 | 来源:发表于2018-07-17 14:12 被阅读10次

    1.Channel

    Channel中有EventLoop和ChannelPipeline,

    public interface Channel {
    
        /**
         * Return the {@link EventLoop} this {@link Channel} was registered to.
         */
        EventLoop eventLoop();
    }
    

    1.1 Channel和EventLoop

    在bind时会去做register动作,这个之前分析过
    参考:Netty笔记-Channel的Register

    此时也将EventLoop与Channel关联起来,Channel有了EventLoop便有了异步操作的能力,Channel的很多操作都是异步的,都是EventLoop的功劳
    参考:Netty笔记-GlobalEventExecutor

            @Override
            public final void register(EventLoop eventLoop, final ChannelPromise promise) {
                if (eventLoop == null) {
                    throw new NullPointerException("eventLoop");
                }
                if (isRegistered()) {
                    promise.setFailure(new IllegalStateException("registered to an event loop already"));
                    return;
                }
                if (!isCompatible(eventLoop)) {
                    promise.setFailure(
                            new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
                    return;
                }
    
                AbstractChannel.this.eventLoop = eventLoop;
    
                if (eventLoop.inEventLoop()) {
                    register0(promise);
                } else {
                    try {
                        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);
                    }
                }
            }
    

    1 .2 使用EventLoop进行异步操作

    我们会发现在代码中大量出现如下模式的代码

    if (eventLoop.inEventLoop()) {
                    
                } else {
                    try {
                        eventLoop.execute(new Runnable() {
                            @Override
                            public void run() {
                            }
                        });
                    }
    }
    

    所以上面的register0(promise)这段代码是异步执行的

    相关文章

      网友评论

          本文标题:Netty笔记-Channel和EventLoop

          本文链接:https://www.haomeiwen.com/subject/izbwpftx.html