1、NioEventLoopGroup构造函数
public class NioEventLoopGroup extends MultithreadEventLoopGroup
public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup
该初始化层层调用知道super 进入MultithreadEventExecutorGroup 的Line56,如下
Fig 1
2、MultithreadEventLoopGroup
从该类的名字看出三个特征1、多线程,2一个(Executor)数组 ;3、loop轮询数组。
此类的主要作用是初始化DEFAULT_EVENT_LOOP_THREADS,没有新增的方法。
Fig 2
3、MultithreadEventExecutorGroup
Fig 3
Fig 1中line62 MultithreadEventExecutorGroup 的newDefaultThreadFactory()实际调用的是它的子类MultithreadEventLoopGroup的方法。如Fig 4的Line63
这反映的是重写方法的调用流程。
Fig4
Fig 5
如果细心会发现executor的构造函数的入参DefaultThreadFactory的prefix值是“nioEventLoopGroup-2-”。意思是该executor被
children[i] = newChild(executor, args)得到的每一个eventloop都是以prefix为前缀,而Fig4中DEFAULT_EVENT_LOOP_THREADS或nThreads就指定了eventloop的个数。newChild方法见Fig 6;那么nioEventLoopGroup-1-(见Filg7),它被DefaultThreadFactory使用了,见Fig3中成员实例terminationFuture。而执行任务的workerGroup newChild的loop的prefix是nioEventLoopGroup-3-。
@Override
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
return new NioEventLoop(this, executor, (SelectorProvider) args[0]);
}
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider) {
super(parent, executor, false);
if (selectorProvider == null) {
throw new NullPointerException("selectorProvider");
}
provider = selectorProvider;
selector = openSelector();
}
private Selector openSelector() {
final Selector selector;
try {
selector = provider.openSelector();
} catch (IOException e) {
throw new ChannelException("failed to open a new selector", e);
}
if (DISABLE_KEYSET_OPTIMIZATION) {
return selector;
}
try {
SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();
Class<?> selectorImplClass =
Class.forName("sun.nio.ch.SelectorImpl", false, ClassLoader.getSystemClassLoader());
// Ensure the current selector implementation is what we can instrument.
if (!selectorImplClass.isAssignableFrom(selector.getClass())) {
return selector;
}
Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");
selectedKeysField.setAccessible(true);
publicSelectedKeysField.setAccessible(true);
selectedKeysField.set(selector, selectedKeySet);
publicSelectedKeysField.set(selector, selectedKeySet);
selectedKeys = selectedKeySet;
logger.trace("Instrumented an optimized java.util.Set into: {}", selector);
} catch (Throwable t) {
selectedKeys = null;
logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t);
}
return selector;
}
F
Fig 7