NioEventLoopGroup

1563534229444.png

启动

线程数

public NioEventLoopGroup() {
    this(0);
}

protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args){
    super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
// 默认是CPU核心数*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) {                                     // 创建线程executor
        if (executor == null) {
            executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
        }

        // 初始化EventExecutor数组
        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 {
        // 创建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);
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容