Netty Selector 优化

创建 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 类有两个字段:unwrappedSelectorselector,它们都是 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 优化,unwrappedSelectorselector 字段保存的都是原生 Selector

Selector 的优化逻辑位于 openSelector(),以下分为多个部分讲解:

try {
    unwrappedSelector = provider.openSelector(); 
} catch (IOException e) {
    throw new ChannelException("failed to open a new selector", e);
}

provider 在 Linux 系统中保存的是 EPollSelectorProvider 对象。

调用 EPollSelectorProvideropenSelector() 方法获取原生 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 类中的 selectedKeyspublicSelectedKeys 2 个字段。如果原生 Selector 没有继承 sun.nio.ch.SelectorImpl 这个类,自然也不存在那两个字段,何谈优化呢。

final Class<?> selectorImplClass = (Class<?>) maybeSelectorImplClass;
final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet();

我们会创建一个 SelectedSelectionKeySet 类型的对象,用来替换原生 Selector 对象(继承了sun.nio.ch.SelectorImpl)中的 selectedKeyspublicSelectedKeys 字段值。

我们来看下 SelectedSelectionKeySetSelectorImpl 两个类中的字段。

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 类中的 selectedKeyspublicSelectedKeys 字段都是 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() 提升权限,绕过安全管理器限制。这是必要的,因为 SelectorImplselectedKeyspublicSelectedKeys 字段是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 封装到一起返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值