
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);
}
}