首页  

ConcurrentHashMap读不需要加锁的秘密     所属分类 java 浏览量 1179
Java8

final 
volatile 
sun.misc.Unsafe.getObjectVolatile




public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }

大量使用 volatile  保证可见性
transient volatile Node<K,V>[] table;


static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;
        

注意 key hash 使用 final ,不可变,可保证可见性
val  next 使用 volatile


static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}

// Unsafe mechanics
private static final sun.misc.Unsafe U;
    
获取 table 里的 node  使用    U.getObjectVolatile !!!

sun.misc.Unsafe.getObjectVolatile(Object, long),保证读到的是最新的对象。



上一篇     下一篇
hashmap在java7和8中的区别

java位运算

HashMap和ConcurrentHashMap中的hash函数

ConcurrentHashMap size 实现要点

37种融资模式

企业分析要点