NioEventLoop
NioEventLoop 创建
new NioEventLoopGroup 线程组,默认 2*cpu
new ThreadPerTaskExecutor() 线程创建器,创建 NioEventLoop 底层的线程
循环调用 newChild() 创建 NioEventLoop
chooserFactory.newChooser() 线程选择器,为每个新链接分配 NioEventLoop 线程
ThreadPerTaskExecutor
每次只需任务时都会创建一个线程实体
NioEventLoop 线程命名规则 nioEventLoop-1-xx : -1代表第几个 NioEventLoopGroup
DefaultThreadFactory
MultithreadEventExecutorGroup#MultithreadEventExecutorGroup()
protected MultithreadEventExecutorGroup(int nThreads
, Executor executor
,
EventExecutorChooserFactory chooserFactory
, Object
... args
) {
if (nThreads
<= 0) {
throw new IllegalArgumentException(String
.format("nThreads: %d (expected: > 0)", nThreads
));
}
if (executor
== null
) {
executor
= new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
children
= new EventExecutor[nThreads
];
for (int i
= 0; i
< nThreads
; i
++) {
boolean success
= false;
try {
children
[i
] = newChild(executor
, args
);
success
= true;
} catch (Exception e
) {
throw new IllegalStateException("failed to create a child event loop", e
);
} finally {
if (!success
) {
for (int j
= 0; j
< i
; j
++) {
children
[j
].shutdownGracefully();
}
for (int j
= 0; j
< i
; j
++) {
EventExecutor e
= children
[j
];
try {
while (!e
.isTerminated()) {
e
.awaitTermination(Integer
.MAX_VALUE
, TimeUnit
.SECONDS
);
}
} catch (InterruptedException interrupted
) {
Thread
.currentThread().interrupt();
break;
}
}
}
}
}
chooser
= chooserFactory
.newChooser(children
);
final FutureListener
<Object> terminationListener
= new FutureListener<Object>() {
@Override
public void operationComplete(Future
<Object> future
) throws Exception
{
if (terminatedChildren
.incrementAndGet() == children
.length
) {
terminationFuture
.setSuccess(null
);
}
}
};
for (EventExecutor e
: children
) {
e
.terminationFuture().addListener(terminationListener
);
}
Set
<EventExecutor> childrenSet
= new LinkedHashSet<EventExecutor>(children
.length
);
Collections
.addAll(childrenSet
, children
);
readonlyChildren
= Collections
.unmodifiableSet(childrenSet
);
}
newChild 逻辑
保存线程执行器 ThreadPerTaskExecutor 创建一个 MpscQueue 创建一个 selector
方法: io.netty.channel.nio.NioEventLoopGroup#newChild
newChild()
NioEventLoopGroup.newChild()
NioEventLoop构造方法:创建selector,关联NioEventLoop
newTaskQueue()创建MPSC队列
创建 chooser
// 设置 chooserFactory,用来实现从线程池中选择一个线程的选择策略 chooser = chooserFactory.newChooser(children);
方法: io.netty.util.concurrent.DefaultEventExecutorChooserFactory#newChooser
public EventExecutorChooser
newChooser(EventExecutor
[] executors
) {
if (isPowerOfTwo(executors
.length
)) {
return new PowerOfTwoEventExecutorChooser(executors
);
} else {
return new GenericEventExecutorChooser(executors
);
}
}