zoukankan      html  css  js  c++  java
  • netty DefaultAttributeMap(比hashmap节省空间)源码学习AtomicReferenceArray/AtomicReference/ConcurrentHashMap乐观锁cas/悲观锁synchronized

    DefaultAttributeMap  :

    private volatile AtomicReferenceArray<DefaultAttribute<?>> attributes;

    寻址方式:

    Attributekey父类:

    public abstract class AbstractConstant<T extends AbstractConstant<T>> implements Constant<T> {
    ...
    @Override
    public final int id() {
    return id;
    }

    DefaultAttributeMap里的"table":
    attributes = new AtomicReferenceArray<DefaultAttribute<?>>(BUCKET_SIZE);
    ...
    private static final int BUCKET_SIZE = 4;
    private static final int MASK = BUCKET_SIZE - 1;
    ...
    index寻址函数:
    与运算相比hashmap中的hashcode操作,效率更高
    return key.id() & MASK;

    乐观锁:

    cas:

    attributes.compareAndSet(i, null, head)

    悲观锁:

    synchronized:

    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;
    }
    }

    ConcurrentHashMap  :   

    transient volatile Node<K,V>[] table;
    乐观锁:
    cas:
    casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null))
    悲观锁:
    synchronized:
    synchronized (f) {
    if (tabAt(tab, i) == f) {
    if (fh >= 0) {
    binCount = 1;
    for (Node<K,V> e = f;; ++binCount) {
    K ek;
    if (e.hash == hash &&
    ((ek = e.key) == key ||
    (ek != null && key.equals(ek)))) {
    oldVal = e.val;
    if (!onlyIfAbsent)
    e.val = value;
    break;
    }
    Node<K,V> pred = e;
    if ((e = e.next) == null) {
    pred.next = new Node<K,V>(hash, key,
    value, null);
    break;
    }
    }
    }
    else if (f instanceof TreeBin) {
    Node<K,V> p;
    binCount = 2;
    if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
    value)) != null) {
    oldVal = p.val;
    if (!onlyIfAbsent)
    p.val = value;
    }
    }
    }
    hashmap寻址方式自然是hashcode()
  • 相关阅读:
    AndroidStudio开发体温上报系统------问题总结
    AndroidStudio--app是如何运行的
    sqlite操作
    sqlite数据库
    Android Service
    echart自定义主题
    vue监听数组变化
    Django:数据库驱动安装
    pycharm链接mysql报错: Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTimezone' property manually.
    Django2.2:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
  • 原文地址:https://www.cnblogs.com/CreatorKou/p/11950272.html
Copyright © 2011-2022 走看看