NioEventLoop源码之openSelector优化

构造函数

NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
                 SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
        super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
        if (selectorProvider == null) {
            throw new NullPointerException("selectorProvider");
        }
        if (strategy == null) {
            throw new NullPointerException("selectStrategy");
        }
        provider = selectorProvider;
        final SelectorTuple selectorTuple = openSelector(); //SelectorProvider.provider().openSelector()
        selector = selectorTuple.selector; // SelectedSelectionKeySetSelector  包装unwrappedSelector
        unwrappedSelector = selectorTuple.unwrappedSelector; //原始的nio创建对象  比如WindowsSelectorImpl
        selectStrategy = strategy; // DefaultSelectStrategy
    }

openSelector 优化

private SelectorTuple openSelector() {
        final Selector unwrappedSelector;
        try {
            unwrappedSelector = provider.openSelector(); //创建java原生selector
        } catch (IOException e) {
            throw new ChannelException("failed to open a new selector", e);
        }
        //是否需要优化,默认需要DISABLE_KEYSET_OPTIMIZATION=false
        if (DISABLE_KEY_SET_OPTIMIZATION) {
            return new SelectorTuple(unwrappedSelector);
        }
        //尝试获取sun.nio.ch.SelectorImpl的class对象
        Object maybeSelectorImplClass = AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                try {
                    return Class.forName(
                            "sun.nio.ch.SelectorImpl",
                            false,
                            PlatformDependent.getSystemClassLoader());
                } catch (Throwable cause) {
                    return cause;
                }
            }
        });
        //如果返回maybeSelectorImplClass不是一个class对象,或者maybeSelectorImplClass不是(unwrappedSelector.getClass()他的子类
        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); //创建一个SelectorTuple,内部unwrappedSelector并没有被优化
        }
        //selector的class对象
        final Class selectorImplClass = (Class) maybeSelectorImplClass;
        final SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet(); //******注意这里 内部素组结构实现的set接口

        Object maybeException = AccessController.doPrivileged(new PrivilegedAction() {
            @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);  //把selectedKeys设置为SelectedSelectionKeySet(它是数组实现),原来是HashSet,也就是用HashMap实现
                    publicSelectedKeysField.set(unwrappedSelector, selectedKeySet); //把publicSelectedKeys设置为SelectedSelectionKeySet(它是数组实现),原来是HashSet,也就是用HashMap实现
                    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); //返回SelectorTuple,内部unwrappedSelector并没有被优化
        }
        selectedKeys = selectedKeySet;
        logger.trace("instrumented a special java.util.Set into: {}", unwrappedSelector);
        return new SelectorTuple(unwrappedSelector,
                                 new SelectedSelectionKeySetSelector(unwrappedSelector, selectedKeySet));
    } 
  
WindowsSelectorImpl 

final class WindowsSelectorImpl extends SelectorImpl {}


public abstract class SelectorImpl extends AbstractSelector {
    protected Set selectedKeys = new HashSet();  //selectedKeys 

    ....................

    protected SelectorImpl(SelectorProvider var1) {
        super(var1);
        if (Util.atBugLevel("1.4")) {
            this.publicKeys = this.keys;
            this.publicSelectedKeys = this.selectedKeys; // 其实就是selectedKeys 
        } else {
            this.publicKeys = Collections.unmodifiableSet(this.keys);
            this.publicSelectedKeys = Util.ungrowableSet(this.selectedKeys); 其实就是selectedKeys 
        }

    }

 

SelectedSelectionKeySet 

final class SelectedSelectionKeySet extends AbstractSet {

    SelectionKey[] keys;
    int size;

    SelectedSelectionKeySet() {
        keys = new SelectionKey[1024];
    }

}

 

SelectorTuple
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; // SelectedSelectionKeySetSelector  这里的delegate=unwrappedSelector
        }
    }




//是否关闭优化,默认需要DISABLE_KEYSET_OPTIMIZATION=false
if (DISABLE_KEY_SET_OPTIMIZATION) {
      return new SelectorTuple(unwrappedSelector);
}

SelectedSelectionKeySetSelector 

final class SelectedSelectionKeySetSelector extends Selector {
    private final SelectedSelectionKeySet selectionKeys;
    private final Selector delegate;

    SelectedSelectionKeySetSelector(Selector delegate, SelectedSelectionKeySet selectionKeys) {
        this.delegate = delegate; // jdk原生Selector的实现类
        this.selectionKeys = selectionKeys; //数组实现的SelectedSelectionKeySet
    }

}

 

    在windows操作系统下,openSelector,在优化情况下,本质就是把Selector的实现类WindowsSelectorImpl中的selectedKeys、publicSelectedKeys替换为新的Netty自己实现的SelectedSelectionKeySet(数组实现)

    以前的selectedKeys和publicSelectedKeys是hashset实现的,而hashset其实就是1个hashmap   
 
    返回的SelectorTuple, 关闭优化情况下,Selector unwrappedSelector 和 Selector selector 是同一个,都是jdk的原生Selector的实现。 

         未关闭优化情况下,调用 SelectorTuple(Selector unwrappedSelector, Selector selector) 构造函数,则selector是SelectedSelectionKeySetSelector类,内部delegate是原生的Selector实现类,selectionKeys是Netty自己数组实现的SelectedSelectionKeySet

 

 


 

 

 

 

 

 

 

你可能感兴趣的:(netty)