
io.netty.channel.AbstractChannel.AbstractUnsafe#register
開始注冊(cè)
if (eventLoop.inEventLoop()) {
register0(promise);
} else {
try {
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
} catch (Throwable t) {
}
}
進(jìn)入 io.netty.util.concurrent.SingleThreadEventExecutor#execute,SingleThreadEventExecutor重寫線程池的execute方法
- 添加register0到任務(wù)隊(duì)列
- 會(huì)調(diào)用線程start
inEventLoop()方法用來(lái)判斷當(dāng)前是否在EventLoop線程執(zhí)行,注冊(cè)的時(shí)候是在main線程執(zhí)行的,所以為false。
eventLoop.execute
@Override
public void execute(Runnable task) {
if (task == null) {
throw new NullPointerException("task");
}
boolean inEventLoop = inEventLoop();
if (inEventLoop) {
addTask(task);
} else {
startThread();
addTask(task);
if (isShutdown() && removeTask(task)) {
reject();
}
}
if (!addTaskWakesUp && wakesUpForTask(task)) {
wakeup(inEventLoop);
}
}
register0
斷點(diǎn) io.netty.channel.AbstractChannel.AbstractUnsafe#register0
SingleThreadEventExecutor的Thread運(yùn)行的是NioEventLoop的run。

doRegister();
pipeline.invokeHandlerAddedIfNeeded();
pipeline.fireChannelRegistered();
doRegister 會(huì)綁定channel到selector
invokeHandlerAddedIfNeeded
斷點(diǎn) ServerBootstrap 181
斷點(diǎn) SimpleServerHandler#handlerAdded
斷點(diǎn) ServerBootstrap 193
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
ChannelHandler handler = handler();
if (handler != null) {
pipeline.addLast(handler);//斷點(diǎn)
}
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
});
調(diào)用pipeline.addLast(handler);之前,pipeline中只有head ServerBootstrap$1#0 tail
調(diào)用之后,pipeline中有 head ServerBootstrap$1#0 SimpleServerHandler tail
函數(shù)返回后,進(jìn)入
io.netty.channel.ChannelInitializer#initChannel(io.netty.channel.ChannelHandlerContext)
if (initMap.putIfAbsent(ctx, Boolean.TRUE) == null) { // Guard against re-entrance.
try {
initChannel((C) ctx.channel());
} catch (Throwable cause) {
// Explicitly call exceptionCaught(...) as we removed the handler before calling initChannel(...).
// We do so to prevent multiple calls to initChannel(...).
exceptionCaught(ctx, cause);
} finally {
remove(ctx);
}
return true;
}
然后會(huì)把ServerBootstrap$1#0刪除。
另外,對(duì)于pipeline添加ServerBootstrapAcceptor,會(huì)以任務(wù)方式提交到隊(duì)列。

fireChannelRegistered
SimpleServerHandler#channelRegistered