【netty】AttributeKey、AttributeMap、Attribute

1. attributeKey

attributeKey.png

1.1 ConstantPool

这个类主要是来缓存一些常量,和我之前写的cache类似的思想。
提供了3个关键的方法,valueOf、exists、newInstance,其中我们真正缓存容器还是jdk提供的 ConcurrentHashMap

1.1.1 valueOf

可以看出最关键的方法是 getOrCreate,这个方法最大的特点是采用类乐观锁的方式,当我们最后发现了 constant != null时,那么我们返回已经插入的 constant

    public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
        return valueOf(firstNameComponent.getName() + '#' + secondNameComponent);
    }

    public T valueOf(String name) {
        return getOrCreate(name);
    }

    private T getOrCreate(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;
            }
        }
        return constant;
    }
1.1.2 newInstance

可以看出最关键的方法是 createOrThrow,这个方法最大的特点是采用类乐观锁的方式,当我们最后发现了 constant != null时,我们直接抛出异常。

    public T newInstance(String name) {
        return createOrThrow(name);
    }
    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));
    }
1.1.3 valueOf和newInstance 对比

valueOf:如果 name 不存在就创建一个,且多线程随先创建返回谁。
newInstance : 如果name存在就抛出异常,且多线程创建,除了成功创建的那个线程外,其他线程抛出异常。

1.2 AttributeKey

AttributeKey是基于ConstantPool进行缓存的。

1.2.1 创建

可以看出,每个newConstant的id,是nextId,是逐渐递增。

//AttributeKey
private static final ConstantPool<AttributeKey<Object>> pool = new ConstantPool<AttributeKey<Object>>() {
        @Override
        protected AttributeKey<Object> newConstant(int id, String name) {
            return new AttributeKey<Object>(id, name);
        }
};

//ConstantPool
private T getOrCreate(String name) {
            final T tempConstant = newConstant(nextId(), name);
}
private T createOrThrow(String name) {
            final T tempConstant = newConstant(nextId(), name);
}

private final AtomicInteger nextId = new AtomicInteger(1);
@Deprecated
    public final int nextId() {
        return nextId.getAndIncrement();
    }

2.AttributeMap

AttributeMap.png

可以看出,唯一的实现类就是DefaultAttributeMap。
就两方法,attr 和 hasAttr。

2.1 DefaultAttributeMap

2.1.1 为啥要自己重新设计一个map类?

作者做出了解释

Not using ConcurrentHashMap due to high memory consumption.

显然,在大量连接数下,ConcurrentHashMap 显得非常吃内存,作者做出一定的抉择。

2.1.1 这个类的优点和缺点

优点:
代码少,简单,占用内存相对较小。

缺点:

  1. 单利模式没设计好,显然传统的double-check更优秀。
    可以看出,在多线程竞争下,attributes 可能创建多次,而传统的 double-check 只会创建一次。
    if (attributes == null) {
            attributes = new AtomicReferenceArray<DefaultAttribute<?>>(BUCKET_SIZE);
            if (!updater.compareAndSet(this, null, attributes)) {
                attributes = this.attributes;
            }
        }
  1. key在极端情况下可能练成一条线
    可以看出,最关键的还是key.id()这个方法,而这个方法是通过每次++一个int生成,在极端情况下,多次不同的key可以得到同一个index,这样结果显然不如直接array数组来的好
    int i = index(key);

    private static int index(AttributeKey<?> key) {
        return key.id() & MASK;
    }
2.1.3 设计思想

通过 AttributeKey的id做一个划分,来做个分段锁。使用数组+链表作结构。
客观的评价,这个类写的勉勉强强

2.1.4 attr(AttributeKey<T> key)

这是一个通过AttributeKey 获取 Attribute 的方法。如果找不到对应的Attribute ,就创建一个 Attribute

可以看出一个数组加链表的结构,且链表第一个元素必须为 空的DefaultAttribute元素,用来防止回滚

public <T> Attribute<T> attr(AttributeKey<T> key) {

    //我觉得double-check更好
        AtomicReferenceArray<DefaultAttribute<?>> attributes = this.attributes;
        if (attributes == null) {
            // Not using ConcurrentHashMap due to high memory consumption.
            attributes = new AtomicReferenceArray<DefaultAttribute<?>>(BUCKET_SIZE);

            if (!updater.compareAndSet(this, null, attributes)) {
                attributes = this.attributes;
            }
        }

        int i = index(key);
        DefaultAttribute<?> head = attributes.get(i);
        if (head == null) {
            // No head exists yet which means we may be able to add the attribute without synchronization and just
            // use compare and set. At worst we need to fallback to synchronization and waste two allocations.
            head = new DefaultAttribute();//主要是 attributes.compareAndSet会引起替换操作,这里就是避免替换后还要回滚。
            DefaultAttribute<T> attr = new DefaultAttribute<T>(head, key);
            head.next = attr;
            attr.prev = head;
            if (attributes.compareAndSet(i, null, head)) {
                // we were able to add it so return the attr right away
                return attr;
            } else {
                head = attributes.get(i);
            }
        }

        synchronized (head) {
            DefaultAttribute<?> curr = head;
            for (;;) {
                DefaultAttribute<?> next = curr.next;
                if (next == null) {//如果一直找不到就生成一个
                    DefaultAttribute<T> attr = new DefaultAttribute<T>(head, key);
                    curr.next = attr;
                    attr.prev = curr;
                    return attr;
                }

                if (next.key == key && !next.removed) {//遍历过程
                    return (Attribute<T>) next;
                }
                curr = next;
            }
        }
    }
2.1.4 hasAttr(AttributeKey<T> key)

判断是否含有这个属性。

public <T> boolean hasAttr(AttributeKey<T> key) {
        if (key == null) {
            throw new NullPointerException("key");
        }
        AtomicReferenceArray<DefaultAttribute<?>> attributes = this.attributes;
        if (attributes == null) {
            // no attribute exists
            return false;
        }

        int i = index(key);
        DefaultAttribute<?> head = attributes.get(i);
        if (head == null) {
            // No attribute exists which point to the bucket in which the head should be located
            return false;
        }

        // We need to synchronize on the head.
        synchronized (head) {
            // Start with head.next as the head itself does not store an attribute.
            DefaultAttribute<?> curr = head.next;
            while (curr != null) {
                if (curr.key == key && !curr.removed) {
                    return true;
                }
                curr = curr.next;
            }
            return false;
        }
    }

2.1.5 DefaultAttribute

private static final class DefaultAttribute<T> extends AtomicReference<T> implements Attribute<T> {

        private static final long serialVersionUID = -2661411462200283011L;

        // The head of the linked-list this attribute belongs to
        private final DefaultAttribute<?> head;
        private final AttributeKey<T> key;

        // Double-linked list to prev and next node to allow fast removal
        private DefaultAttribute<?> prev;
        private DefaultAttribute<?> next;

        // Will be set to true one the attribute is removed via getAndRemove() or remove()
        private volatile boolean removed;

        DefaultAttribute(DefaultAttribute<?> head, AttributeKey<T> key) {
            this.head = head;
            this.key = key;
        }

        // Special constructor for the head of the linked-list.
        DefaultAttribute() {
            head = this;
            key = null;
        }

        @Override
        public AttributeKey<T> key() {
            return key;
        }

        @Override
        public T setIfAbsent(T value) {
            while (!compareAndSet(null, value)) {
                T old = get();
                if (old != null) {
                    return old;
                }
            }
            return null;
        }

        @Override
        public T getAndRemove() {
            removed = true;
            T oldValue = getAndSet(null);
            remove0();
            return oldValue;
        }

        @Override
        public void remove() {
            removed = true;
            set(null);
            remove0();
        }

        private void remove0() {
            synchronized (head) {
                if (prev == null) {
                    // Removed before.
                    return;
                }

                prev.next = next;

                if (next != null) {
                    next.prev = prev;
                }

                // Null out prev and next - this will guard against multiple remove0() calls which may corrupt
                // the linked list for the bucket.
                prev = null;
                next = null;
            }
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339