NioEventLoopGroup

1563534229444.png

啟動

線程數(shù)

public NioEventLoopGroup() {
    this(0);
}

protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args){
    super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
// 默認是CPU核心數(shù)*2
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(        "io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2));

初始化

protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
                                            EventExecutorChooserFactory chooserFactory,                                             Object... args) {                                     // 創(chuàng)建線程executor
        if (executor == null) {
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }

        // 初始化EventExecutor數(shù)組
        children = new EventExecutor[nThreads];

        for (int i = 0; i < nThreads; i ++) {
            boolean success = false;
            try {
                // 初始化NioEventLoop
                children[i] = newChild(executor, args);
                success = true;
            } 
            
        }
        // 生成選擇器
        chooser = chooserFactory.newChooser(children);

    }

ThreadPerTaskExecutor

public ThreadPerTaskExecutor(ThreadFactory threadFactory) {
        if (threadFactory == null) {
            throw new NullPointerException("threadFactory");
        }
        this.threadFactory = threadFactory;
    }

    @Override
    public void execute(Runnable command) {
        threadFactory.newThread(command).start();
    }

newChild

protected EventLoop newChild(Executor executor, Object... args) throws Exception {
        // 創(chuàng)建NioEventLoop
        return new NioEventLoop(this, executor, (SelectorProvider) args[0],
            ((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
    }

chooser

public EventExecutorChooser newChooser(EventExecutor[] executors) {
        // 長度是否是2的冪, 來決定next的下標怎么計算,位運算比求余要快得多
        if (isPowerOfTwo(executors.length)) {
            // idx.getAndIncrement() & executors.length - 1
            return new PowerOfTowEventExecutorChooser(executors);
        } else {
            // idx.getAndIncrement() % executors.length)
            return new GenericEventExecutorChooser(executors);
        }
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容