美文网首页
NioEventLoopGroup

NioEventLoopGroup

作者: Pillar_Zhong | 来源:发表于2019-08-01 16:50 被阅读0次
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);
        }
    }

相关文章

网友评论

      本文标题:NioEventLoopGroup

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