在浏览 Netty 代码库时,我在 NioEventLoop.java 中看到了下面的代码块。
SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();
Class<?> selectorImplClass =
Class.forName("sun.nio.ch.SelectorImpl", false, PlatformDependent.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;
Netty为什么要用反射来改变java库类sun.nio.ch.SelectorImpl的一个成员?
我看到一个优势,而不是使用 Java 集合中的 Set,而是使用基于数组的 Set,我相信这会更快。还有其他具体原因吗?
最佳答案
主要是为了减少GC。 Trustin 在这里做了一些测试,发现这更有效。
关于java - 为什么 Netty 使用反射将 sun.nio.ch.SelectorImpl 类中的成员替换为基于数组的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550412/