netty DefaultAttributeMap(比hashmap节省空间)源码学习AtomicReferenceArray/AtomicReference/ConcurrentHashMap乐观锁...

本文深入探讨了DefaultAttributeMap和ConcurrentHashMap等并发集合的内部实现,包括寻址方式、乐观锁与悲观锁的应用。通过对比不同寻址函数的效率,以及详细解析CAS和synchronized在并发控制中的作用,为读者提供了对并发编程更深层次的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值