java - 为什么 Netty 使用反射将 sun.nio.ch.SelectorImpl 类中的成员替换为基于数组的集合?

标签 java reflection netty nio

在浏览 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/

相关文章:

cassandra - 失败 : Connection reset by peer

java - 尝试使用循环来处理备用数组

java - 我应该将超时设置为 "getting connection from pool"吗?

Java InputStream读取多部分消息

json - 反编码反射值

c++ - 仅为派生类启用模板化基类

java - ChannelOutboundHandlerAdapter 未被调用

Spring UnsatisfiedDependencyException 且不是托管类型 : class java. lang.Object

.net - 为什么可以使用反射从签名程序集中加载未签名程序集中的类型?

java - Netty中如何拒绝传入连接?