创建EventLoopGroup使用无参构造方法时,发现会创建24个NioEventLoop(readonlyChildren.size=24),经查,是取的java虚拟机的可用处理器数2倍。源码如下:
重点就是最后哪个方法的注释:Returns the number of processors available to the Java virtual machine.(返回Java虚拟机可用的处理器数。)
/**
* @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...)
*/
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
//如果没指定线程数,则取默认的DEFAULT_EVENT_LOOP_THREADS
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
private static final int DEFAULT_EVENT_LOOP_THREADS;
static {
//核心逻辑就是看NettyRuntime.availableProcessors() * 2
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
}
}
/**
* Get the configured number of available processors. The default is {@link Runtime#availableProcessors()}.
* This can be overridden by setting the system property "io.netty.availableProcessors" or by invoking
* {@link #setAvailableProcessors(int)} before any calls to this method.
*
* @return the configured number of available processors
*/
@SuppressForbidden(reason = "to obtain default number of available processors")
synchronized int availableProcessors() {
//如果availableProcessors =0,还未设置过,就取Runtime.getRuntime().availableProcessors()
if (this.availableProcessors == 0) {
final int availableProcessors =
SystemPropertyUtil.getInt(
"io.netty.availableProcessors",
Runtime.getRuntime().availableProcessors());
setAvailableProcessors(availableProcessors);
}
return this.availableProcessors;
}
}
/**
* Returns the number of processors available to the Java virtual machine.
*
* <p> This value may change during a particular invocation of the virtual
* machine. Applications that are sensitive to the number of available
* processors should therefore occasionally poll this property and adjust
* their resource usage appropriately. </p>
*
* @return the maximum number of processors available to the virtual
* machine; never smaller than one
* @since 1.4
*/
public native int availableProcessors();