In the last section we found ServerSocketChannel generation, Selector registration, bound port startup and so on: How does Netty block ServerSocketChannel startup, and then validate the use of Selector generation in Netty and how does our JDK native worker start working in Netty: NioEventLoopGroup
Example source: github.com/jsbintask22…
NioEventLoopGroup
NioEventLoopGroup
SelectProvider
ThreadPerTaskExecutor
And start
Further down, it instantiates all children and that children is an array of NioEventLoop instances (dropping the executor above);
So now the key thing is, when did this NioEventLoop lose a task to ThreadPerTaskExecutor, so let’s keep tracking it NioEventLoop
We have as many selectors as we have threads in the children array
Let’s go back to the registerAndInit() method that was resolved in the previous section
public boolean inEventLoop(Thread thread) {
return thread == this.thread;
}
Copy the code
That is, go down first
eventLoop.execute(new Runnable() {
@Override
public void run(a) { register0(promise); }});Copy the code
Finally start a new thread using executor commit (remember ThreadPerTaskExecutor) :
NioEventLoop.run()
processSelectedKeys
processSelectedKey
NioMessageUnsafe.read ()
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
SocketChannel ch = SocketUtils.accept(javaChannel());
try {
if(ch ! =null) {
buf.add(new NioSocketChannel(this, ch));
return 1; }}catch (Throwable t) {
logger.warn("Failed to create a new channel from an accepted socket.", t);
try {
ch.close();
} catch (Throwable t2) {
logger.warn("Failed to close a socket.", t2); }}return 0;
}
Copy the code
ServerBootstrapAcceptor’s read method is triggered in the pipeline on SererSocketChannel. The newly accepted SocketChannel is registered with the selector again, and the work child thread starts an infinite loop and performs the above operations:
ch.eventLoop().execute