创建 NioEventLoop
对象时,会调用 openSelector()
获取一个 Selector
。
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
.....
provider = selectorProvider;
final SelectorTuple selectorTuple = openSelector();
selector = selectorTuple.selector;
unwrappedSelector = selectorTuple.unwrappedSelector;
.....
}
SelectorTuple
类有两个字段:unwrappedSelector
和 selector
,它们都是 Selector
类型。
private static final class SelectorTuple {
final Selector unwrappedSelector;
final Selector selector;
SelectorTuple(Selector unwrappedSelector) {
this.unwrappedSelector = unwrappedSelector;
this.selector = unwrappedSelector;
}
SelectorTuple(Selector unwrappedSelector, Selector selector) {
this.unwrappedSelector = unwrappedSelector;
this.selector = selector;
}
}
其中 unwrappedSelector
保存的是原生 Selector
;而 selector
保存的是优化后的 Selector
。
如果系统没有启用 Selector 优化,unwrappedSelector
和 selector
字段保存的都是原生 Selector
。
Selector
的优化逻辑位于 openSelector()
,以下分为多个部分讲解:
try {
unwrappedSelector = provider.openSelector();
} catch (IOException e) {
throw new ChannelException("failed to open a new selector", e);
}
provider
在 Linux 系统中保存的是 EPollSelectorProvider
对象。
调用 EPollSelectorProvider
的 openSelector()
方法获取原生 Selector,即 EPollSelectorImpl
对象。
if (DISABLE_KEY_SET_OPTIMIZATION) {
return new SelectorTuple(unwrappedSelector);
}
如果没有启用 Selector 优化,则使用原生的 Selector。
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;
}
}
});
获取 sun.nio.ch.SelectorImpl
的 Class 对象。
虽然不同的系统,Selector
的实现也各不相同,但是共同点是,它们都会继承 sun.nio.ch.SelectorImpl
。以 Linux 的 EPollSelectorImpl 为例:
class EPollSelectorImpl extends SelectorImpl
{
.....
}
EPollSelectorImpl 继承了 sun.nio.ch.SelectorImpl
类。
接下来就是类型校验代码
if (!(maybeSelectorImplClass instanceof Class) ||
// 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);
}
如果返回 maybeSelectorImplClass
不是 Class 对象,或者 sun.nio.ch.SelectorImpl
不是原生 Selector
的父类。这两种情况都不能进行 Selector
优化。原因也很简单,我们优化的就是 sun.nio.ch.SelectorImpl
类中的 selectedKeys
和 publicSelectedKeys
2 个字段。如果原生 Selector 没有继承 sun.nio.ch.SelectorImpl
这个类,自然也不存在那两个字段,何谈优化呢。
final Class<?> selectorImplClass = (Class<?>) maybeSelectorImplClass;
final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();
我们会创建一个 SelectedSelectionKeySet
类型的对象,用来替换原生 Selector 对象(继承了sun.nio.ch.SelectorImpl
)中的 selectedKeys
和 publicSelectedKeys
字段值。
我们来看下 SelectedSelectionKeySet
和 SelectorImpl
两个类中的字段。
public abstract class SelectorImpl extends AbstractSelector {
protected Set<SelectionKey> selectedKeys = new HashSet();
....
private Set<SelectionKey> publicSelectedKeys;
....
}
final class SelectedSelectionKeySet extends AbstractSet<SelectionKey> {
SelectionKey[] keys;
int size;
....
}
SelectorImpl
类中的 selectedKeys
和 publicSelectedKeys
字段都是 Set 类型,我们希望使用数组替换 Set 类型,以达到优化的作用。
而 Netty 自定义的 SelectedSelectionKeySet
就是一个包装了数组的类。
SelectedSelectionKeySet
继承了AbstractSet
,目的就是模拟 Set 类型对外提供的接口(如add
),只不过接口内部操作的是数组容器。
HashSet 的 add 方法的时间复杂度是 O(n),扩容时性能更会骤降。当将底层的 HashSet 用数组替换后,向数组中添加数据的时间复杂度是 O(1)。
Object maybeException = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
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;
}
selectedKeysField.set(unwrappedSelector, selectedKeySet);
publicSelectedKeysField.set(unwrappedSelector, selectedKeySet);
return null;
} catch (NoSuchFieldException e) {
return e;
} catch (IllegalAccessException e) {
return e;
}
}
});
通过 AccessController.doPrivileged()
提升权限,绕过安全管理器限制。这是必要的,因为 SelectorImpl
的 selectedKeys
和 publicSelectedKeys
字段是JDK内部私有属性,普通反射会被禁止访问。
若检测到 Java 9+ 且支持 Unsafe(PlatformDependent.hasUnsafe()
),则通过 objectFieldOffset
计算字段内存偏移量,直接写入自定义的 selectedKeySet
。这种方式绕过反射权限检查,避免模块化系统的访问限制。
在 Java 9+ 引入了模块化,若未显式开放
sun.nio.ch
包(如未配置--add-opens
),传统反射会失败,而 Unsafe 方案仍能生效。
若 Unsafe 不可用(如偏移量计算失败或低版本 JDK),则通过反射设置 selectedKeySet
。
selectedKeys = selectedKeySet;
logger.trace("instrumented a special java.util.Set into: {}", unwrappedSelector);
return new SelectorTuple(unwrappedSelector,
new SelectedSelectionKeySetSelector(unwrappedSelector, selectedKeySet));
SelectedSelectionKeySetSelector
就是我们说的优化后的 Selector。
使用 SelectorTuple
将原生和优化后的 Selector 封装到一起返回。