七 Netty 學習:NioEventLoop 對應線程的創建和啟動源碼說明

原文地址:
博客園:Netty 學習(七):NioEventLoop 對應線程的創建和啟動源碼說明
CSDN:Netty 學習(七):NioEventLoop 對應線程的創建和啟動源碼說明
說明在 Netty 服務端代碼中,我們一般會創建了兩個 NioEventLoopGroup:bossGroup 和 workerGroup
其中: bossGroup用于監聽端口,接收新連接的線程組;workerGroup 用于處理每一個連接的數據讀寫的線程組 。
bossGroup 創建第一個 NioEventLoop 線程NioEventLoop 的啟動入口在AbstractUnsafe
        @Override        public final void register(EventLoop eventLoop, final ChannelPromise promise) {            ......            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);                }            }        }其中inEventLoop()方法調用的是AbstractEventExecutor的實現
    @Override    public boolean inEventLoop() {        return inEventLoop(Thread.currentThread());    }而這個實現又調用了子類SingleThreadEventExecutor的如下方法
【七 Netty 學習:NioEventLoop 對應線程的創建和啟動源碼說明】    @Override    public boolean inEventLoop(Thread thread) {        return thread == this.thread;    }在服務端剛啟動的時候,Thread.currentThread()就是當前 main 方法對應的主線程,而this.thread還沒有開始賦值,所以此時為null,
所以eventLoop.inEventLoop()在一開始調用的時候,返回的是 false,進入AbstractUnsafe的如下else邏輯中
        @Override        public final void register(EventLoop eventLoop, final ChannelPromise promise) {            ......            AbstractChannel.this.eventLoop = eventLoop;            // 首次執行的時候 eventLoop.inEventLoop() 返回 false,執行 else 邏輯            if (eventLoop.inEventLoop()) {                ......            } else {               ......                    eventLoop.execute(new Runnable() {                        @Override                        public void run() {                            register0(promise);                        }                    });               ......            }        }

推薦閱讀