• 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()
  • 相关阅读:
    __dopostback的用法
    Asp.net MVC中防止HttpPost重复提交
    分享SQL2005 查询表结构的SQL语句
    SQL Server char nchar varchar nvarchar的区别
    SQL2005中的XXproperty() 函数归纳
    QQ登录端口研究
    关于SQLSERVER的全文目录跟全文索引的区别
    版本管理软件VisualSVN、TortoiseSvn、AnkhSvn 后记
    SCREEN2EXE视频录像软件 提供技术支持的好帮手
    介绍一款替代SSMS的sqlserver管理工具 toad for sqlserver5.7
  • 原文地址:https://www.cnblogs.com/CreatorKou/p/11950272.html
Copyright © 2020-2023  润新知