美文网首页深入浅出Netty源码剖析
Netty源码-常量池ConstantPool

Netty源码-常量池ConstantPool

作者: persisting_ | 来源:发表于2019-06-08 19:49 被阅读1次

    1 概述

    在看Netty服务端启动相关内容时,在配置channel的option和attr时(可参考笔者文章Netty源码-服务端启动过程),看到Netty使用常量池ConstantPool进一步较少了小粒度对象的创建,Netty在提供性能真的是做了许多的努力。

    Netty常量池ConstantPool的实现比较简单,本文也就简单介绍一下。

    2 常量池ConstantPool

    Netty在ServerBootstrap设置通道选项ChannelOption或者属性AttributeKey时都使用了常量池ConstantPool,在AttributeKey中定义了ConstantPool子类如下:

    //AttributeKey
    private static final ConstantPool<AttributeKey<Object>> pool = new ConstantPool<AttributeKey<Object>>() {
        //需要重写其newConstant方法,告诉ConstantPool如果当前变量
        //不在常量池时如何初始化
        @Override
        protected AttributeKey<Object> newConstant(int id, String name) {
            return new AttributeKey<Object>(id, name);
        }
    };
    

    下面直接贴出ConstantPool源码,其代码比较简单,相关说明写在注释里:

    //ConstantPool
    /**
     * A pool of {@link Constant}s.
     *
     * @param <T> the type of the constant
     */
    public abstract class ConstantPool<T extends Constant<T>> {
    
        //常量池使用ConcurrentMap保存常量
        private final ConcurrentMap<String, T> constants = PlatformDependent.newConcurrentHashMap();
    
        //采用递增计数器生成常量ID
        private final AtomicInteger nextId = new AtomicInteger(1);
    
        /**
         * Shortcut of {@link #valueOf(String) valueOf(firstNameComponent.getName() + "#" + secondNameComponent)}.
         */
        //根据Class和String名称获取或生成并返回常量
        public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
            if (firstNameComponent == null) {
                throw new NullPointerException("firstNameComponent");
            }
            if (secondNameComponent == null) {
                throw new NullPointerException("secondNameComponent");
            }
    
            return valueOf(firstNameComponent.getName() + '#' + secondNameComponent);
        }
    
        /**
         * Returns the {@link Constant} which is assigned to the specified {@code name}.
         * If there's no such {@link Constant}, a new one will be created and returned.
         * Once created, the subsequent calls with the same {@code name} will always return the previously created one
         * (i.e. singleton.)
         *
         * @param name the name of the {@link Constant}
         */
        //从常量池中获取指定名称的常量,如果不存在则调用
        //newConstant方法生成新的常量
        public T valueOf(String name) {
            checkNotNullAndNotEmpty(name);
            return getOrCreate(name);
        }
    
        /**
         * Get existing constant by name or creates new one if not exists. Threadsafe
         *
         * @param name the name of the {@link Constant}
         */
        //从常量池中获取常量,如果不包含该常量则新增一个并返回
        private T getOrCreate(String name) {
            //从Map中获取指定名称的常量
            T constant = constants.get(name);
            //如果为空,则新建一个新的常量,并放到常量池中
            if (constant == null) {
                //调用newConstant构造一个新的常量
                final T tempConstant = newConstant(nextId(), name);
                //这里使用putIfAbset,采用了类似懒汉模式单例的
                //Double-Check机制,防止重复put
                constant = constants.putIfAbsent(name, tempConstant);
                //如果返回null,表示double-check检查失败,返回刚新建的
                //常量对象
                if (constant == null) {
                    return tempConstant;
                }
            }
            //返回新建或池中原实例
            return constant;
        }
    
        /**
         * Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}.
         */
         //检查池中是否存在指定名称的常量
        public boolean exists(String name) {
            checkNotNullAndNotEmpty(name);
            return constants.containsKey(name);
        }
    
        /**
         * Creates a new {@link Constant} for the given {@code name} or fail with an
         * {@link IllegalArgumentException} if a {@link Constant} for the given {@code name} exists.
         */
        //返回指定名称的常量实例
        public T newInstance(String name) {
            checkNotNullAndNotEmpty(name);
            return createOrThrow(name);
        }
    
        /**
         * Creates constant by name or throws exception. Threadsafe
         *
         * @param name the name of the {@link Constant}
         */
        //返回池中指定名称对象,如果没有则创建,这里如果putIfAbsent
        //失败会抛出异常
        private T createOrThrow(String name) {
            T constant = constants.get(name);
            if (constant == null) {
                final T tempConstant = newConstant(nextId(), name);
                constant = constants.putIfAbsent(name, tempConstant);
                if (constant == null) {
                    return tempConstant;
                }
            }
    
            throw new IllegalArgumentException(String.format("'%s' is already in use", name));
        }
    
        private static String checkNotNullAndNotEmpty(String name) {
            ObjectUtil.checkNotNull(name, "name");
    
            if (name.isEmpty()) {
                throw new IllegalArgumentException("empty name");
            }
    
            return name;
        }
    
        //供子类重写的方法,用于在未找到指定name的常量时进行初始化
        protected abstract T newConstant(int id, String name);
    
        @Deprecated
        public final int nextId() {
            return nextId.getAndIncrement();
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Netty源码-常量池ConstantPool

        本文链接:https://www.haomeiwen.com/subject/mrtwxctx.html