netty DefaultAttributeMap (hashmap than saving space) source learning AtomicReferenceArray / AtomicReference / ConcurrentHashMap optimistic locking cas / pessimistic locking synchronized

DefaultAttributeMap  :

private volatile AtomicReferenceArray<DefaultAttribute<?>> attributes;

Addressing modes:

Attributekey parent class:

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寻址函数:
Hashcode operation compared with operation in hashmap, more efficient
return key.id() & MASK;

Optimistic lock:

case:

attributes.compareAndSet(i, null, head)

Pessimistic lock:

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; 
optimistic locking:
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()

Guess you like

Origin www.cnblogs.com/CreatorKou/p/11950272.html