关键代码:NioEventLoop => **final SelectorTuple selectorTuple = openSelector();**
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler,
EventLoopTaskQueueFactory queueFactory) {
// parent:this => NioEventLoopGroup
// selectorProvider:SelectorProvider 默认为 SelectorProvider.provider(),该方法可以打开一个 selector 或者 ServerSocketChannel
// strategy:selectStrategyFactory 默认选择策略工厂
// rejectedExecutionHandler:RejectedExecutionHandler 线程拒绝策略,默认为 抛异常
super(parent, executor, false, newTaskQueue(queueFactory), newTaskQueue(queueFactory),
rejectedExecutionHandler);
if (selectorProvider == null) {
throw new NullPointerException("selectorProvider");
}
if (strategy == null) {
throw new NullPointerException("selectStrategy");
}
// provider = SelectorProvider.provider()
provider = selectorProvider;
// ★ 开始创建 selector
// ★ SelectorTuple = [selector = SelectedSelectionKeySetSelector 做了一层包装的 Selector, unwrappedSelector = 替换了 HashSet 的原生 selector]
final SelectorTuple selectorTuple = openSelector();
// ★ selector = SelectedSelectionKeySetSelector 做了一层包装的 Selector
selector = selectorTuple.selector;
// ★ unwrappedSelector = 替换了 HashSet 的原生 selector
unwrappedSelector = selectorTuple.unwrappedSelector;
// selectStrategyFactory 默认选择策略工厂
selectStrategy = strategy;
}
利用反射:**sun.nio.ch.SelectorImpl,将 SelectorImpl 中的 HashSet
private SelectorTuple openSelector() {
final Selector unwrappedSelector;
try {
unwrappedSelector = provider.openSelector();
} catch (IOException e) {
throw new ChannelException("failed to open a new selector", e);
}
if (DISABLE_KEY_SET_OPTIMIZATION) {
return new SelectorTuple(unwrappedSelector);
}
Object maybeSelectorImplClass = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
return Class.forName(
"sun.nio.ch.SelectorImpl",
false,
PlatformDependent.getSystemClassLoader());
} catch (Throwable cause) {
return cause;
}
}
});
if (!(maybeSelectorImplClass instanceof Class) ||
// isAssignableFrom() 方法是从继承的角度来判断,instanceof 关键字是从实例继承的角度来判断
// isAssignableFrom() 方法是判断是否是某个类的父类,instanceof 关键字是判断是否是某个类的子类
// 使用方法:父类.class.isAssignableFrom(子类.class),子类实例 instanceof 父类类型
// ensure the current selector implementation is what we can instrument.
!((Class<?>) maybeSelectorImplClass).isAssignableFrom(unwrappedSelector.getClass())) {
if (maybeSelectorImplClass instanceof Throwable) {
Throwable t = (Throwable) maybeSelectorImplClass;
logger.trace("failed to instrument a special java.util.Set into: {}", unwrappedSelector, t);
}
return new SelectorTuple(unwrappedSelector);
}
final Class<?> selectorImplClass = (Class<?>) maybeSelectorImplClass;
// Netty 自定义的 Set 集合
final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();
Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// selectedKeysField = HashSet<SelectionKey>
Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
// publicSelectedKeysField = HashSet<SelectionKey>
Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");
// 版本判断(可忽略)
if (PlatformDependent.javaVersion() >= 9 && PlatformDependent.hasUnsafe()) {
// Let us try to use sun.misc.Unsafe to replace the SelectionKeySet.
// This allows us to also do this in Java9+ without any extra flags.
long selectedKeysFieldOffset = PlatformDependent.objectFieldOffset(selectedKeysField);
long publicSelectedKeysFieldOffset =
PlatformDependent.objectFieldOffset(publicSelectedKeysField);
if (selectedKeysFieldOffset != -1 && publicSelectedKeysFieldOffset != -1) {
PlatformDependent.putObject(
unwrappedSelector, selectedKeysFieldOffset, selectedKeySet);
PlatformDependent.putObject(
unwrappedSelector, publicSelectedKeysFieldOffset, selectedKeySet);
return null;
}
// We could not retrieve the offset, lets try reflection as last-resort.
}
// 反射设置可对私有属性赋值
Throwable cause = ReflectionUtil.trySetAccessible(selectedKeysField, true);
if (cause != null) {
return cause;
}
// 反射设置可对私有属性赋值
cause = ReflectionUtil.trySetAccessible(publicSelectedKeysField, true);
if (cause != null) {
return cause;
}
// ★★★ 替换了 selectedKeys 原来的 HashSet<SelectionKey> 为 SelectedSelectionKeySet
selectedKeysField.set(unwrappedSelector, selectedKeySet);
// ★★★ 替换了 publicSelectedKeys 原来的 HashSet<SelectionKey> 为 SelectedSelectionKeySet
publicSelectedKeysField.set(unwrappedSelector, selectedKeySet);
return null;
} catch (NoSuchFieldException e) {
return e;
} catch (IllegalAccessException e) {
return e;
}
}
});
// 异常判断(可忽略)
if (maybeException instanceof Exception) {
selectedKeys = null;
Exception e = (Exception) maybeException;
logger.trace("failed to instrument a special java.util.Set into: {}", unwrappedSelector, e);
return new SelectorTuple(unwrappedSelector);
}
// 保存
selectedKeys = selectedKeySet;
logger.trace("instrumented a special java.util.Set into: {}", unwrappedSelector);
// unwrappedSelector 已经替换过底层实现的 selector
return new SelectorTuple(unwrappedSelector,
// 包装了一下 selector,重写了某些方法
new SelectedSelectionKeySetSelector(unwrappedSelector, selectedKeySet));
}