服务端channel的executor赋值
ChannelFuture regFuture = config().group().register(channel);
@Override
public ChannelFuture register(Channel channel) {
//获取EventLoop.SingleThreadEventLoop来注册.MultithreadEventExecutorGroup.next.
EventLoop next = next();
//eventloop和channel注册.
return next.register(channel);
}
@Override
public ChannelFuture register(final ChannelPromise promise) {
ObjectUtil.checkNotNull(promise, "promise");
//unsafe注册.获取channel获取unsafe在注册.
Channel.Unsafe unsafe = promise.channel().unsafe();
//连接和read的unsafe有什么不同.那么秘密是不是都在channel里呢?
unsafe.register(this, promise);
return promise;
}
核心代码: AbstractChannel.this.eventLoop = eventLoop;(NioEventLoop)
@Override
public final void register(EventLoop eventLoop, final ChannelPromise promise) {
ObjectUtil.checkNotNull(eventLoop, "eventLoop");
//是不是已经注册过了.
if (isRegistered()) {
promise.setFailure(new IllegalStateException("registered to an event loop already"));
return;
}
//兼容:Return true if the given EventLoop is compatible with this instance.
if (!isCompatible(eventLoop)) {
promise.setFailure(
new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
return;
}
//eventLoop注册给抽象类的实例.eventLoop绑定给channel.
AbstractChannel.this.eventLoop = eventLoop;
//
if (eventLoop.inEventLoop()) {
register0(promise);
} else {
//main方法或者其他
try {
//这里开始第一次启动线程.注册注册事件.main线程.
eventLoop.execute(new Runnable() {
@Override
public void run() {
register0(promise);
}
});
} catch (Throwable t) {
logger.warn(
"Force-closing a channel whose registration task was not accepted by an event loop: {}",
AbstractChannel.this, t);
closeForcibly();
closeFuture.setClosed();
safeSetFailure(promise, t);
}
}
}
ChannelHandlerContext里的executor是如何赋值的
so easy.
@Override
public EventExecutor executor() {
//如果为空,冲channel里获取.
if (executor == null) {
return channel().eventLoop();
} else {
return executor;
}
}