Java集合之ConcurrentHashMap

Java
309
0
0
2023-09-11

ConcurrentHashMap源码解析

话不多说,先上图

方法太多只能截一半

  1. 这次先介绍字段属性吧,因为可能之前的那种写法我太懒 不想改了,我觉得这样可能更好一点。
   public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
    implements ConcurrentMap<K,V>, Serializable {
    private static final long serialVersionUID =L;
    // 表的最大容量
    private static final int MAXIMUM_CAPACITY = << 30;
    // 默认表的大小
    private static final int DEFAULT_CAPACITY =;
    // 最大数组大小
    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE -;
    // 默认并发数
    private static final int DEFAULT_CONCURRENCY_LEVEL =;
    // 装载因子
    private static final float LOAD_FACTOR =.75f;
    // 转化为红黑树的阈值
    static final int TREEIFY_THRESHOLD =;
    // 由红黑树转化为链表的阈值
    static final int UNTREEIFY_THRESHOLD =;
    // 转化为红黑树的表的最小容量
    static final int MIN_TREEIFY_CAPACITY =;
    // 每次进行转移的最小值
    private static final int MIN_TRANSFER_STRIDE =;
    // 生成sizeCtl所使用的bit位数
    private static int RESIZE_STAMP_BITS =;
    // 进行扩容所允许的最大线程数
    private static final int MAX_RESIZERS = ( << (32 - RESIZE_STAMP_BITS)) - 1;
    // 记录sizeCtl中的大小所需要进行的偏移位数
    private static final int RESIZE_STAMP_SHIFT = - RESIZE_STAMP_BITS;    
    // 一系列的标识
    static final int MOVED     = -; // hash for forwarding nodes
    static final int TREEBIN   = -; // hash for roots of trees
    static final int RESERVED  = -; // hash for transient reservations
    static final int HASH_BITS =x7fffffff; // usable bits of normal node hash
    // 
    /** Number of CPUS, to place bounds on some sizings */
    // 获取可用的CPU个数
    static final int NCPU = Runtime.getRuntime().availableProcessors();
    // 
    /** For serialization compatibility. */
    // 进行序列化的属性
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("segments", Segment[].class),
        new ObjectStreamField("segmentMask", Integer.TYPE),
        new ObjectStreamField("segmentShift", Integer.TYPE)
    };
    
    // 哈希桶数组
    transient volatile Node<K,V>[] table;
    // 下一个哈希桶数组
    private transient volatile Node<K,V>[] nextTable;
    //
    /**
     * Base counter value, used mainly when there is no contention,
     * but also as a fallback during table initialization
     * races. Updated via CAS.
     */
    // 基本计数
    private transient volatile long baseCount;
    //
    /**
     * Table initialization and resizing control.  When negative, the
     * table is being initialized or resized: - for initialization,
     * else -( + the number of active resizing threads).  Otherwise,
     * when table is null, holds the initial table size to use upon
     * creation, or for default. After initialization, holds the
     * next element count value upon which to resize the table.
     */
    // 对表初始化和扩容控制
    private transient volatile int sizeCtl;
    
    /**
     * The next table index (plus one) to split while resizing.
     */
    // 扩容下另一个表的索引
    private transient volatile int transferIndex;

    /**
     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
     */
    // 旋转锁
    private transient volatile int cellsBusy;

    /**
     * Table of counter cells. When non-null, size is a power of.
     */
    // counterCell
    private transient volatile CounterCell[] counterCells;

    // views
    // 视图
    private transient KeySetView<K,V> keySet;
    private transient ValuesView<K,V> values;
    private transient EntrySetView<K,V> entrySet;
    
    // Unsafe mechanics
    private static final sun.misc.Unsafe U;
    private static final long SIZECTL;
    private static final long TRANSFERINDEX;
    private static final long BASECOUNT;
    private static final long CELLSBUSY;
    private static final long CELLVALUE;
    private static final long ABASE;
    private static final int ASHIFT;

    static {
        try {
            U = sun.misc.Unsafe.getUnsafe();
            Class<?> k = ConcurrentHashMap.class;
            SIZECTL = U.objectFieldOffset
                (k.getDeclaredField("sizeCtl"));
            TRANSFERINDEX = U.objectFieldOffset
                (k.getDeclaredField("transferIndex"));
            BASECOUNT = U.objectFieldOffset
                (k.getDeclaredField("baseCount"));
            CELLSBUSY = U.objectFieldOffset
                (k.getDeclaredField("cellsBusy"));
            Class<?> ck = CounterCell.class;
            CELLVALUE = U.objectFieldOffset
                (ck.getDeclaredField("value"));
            Class<?> ak = Node[].class;
            ABASE = U.arrayBaseOffset(ak);
            int scale = U.arrayIndexScale(ak);
            if ((scale & (scale -)) != 0)
                throw new Error("data type scale not a power of two");
            ASHIFT = - Integer.numberOfLeadingZeros(scale);
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}
  1. 接下里还是构造方法吧
  2. 无参构造:ConcurrentHashMap()
  3. 该构造函数用于创建一个带有默认初始容量 (16)、加载因子 (0.75) 和 concurrencyLevel (16) 的新的空映射。
 public ConcurrentHashMap() {   

}

ConcurrentHashMap(int initialCapacity)构造方法

 public ConcurrentHashMap(int initialCapacity) {
    if (initialCapacity <)
        throw new IllegalArgumentException();
    // 找到最接近该容量的的幂次方数(hashMap中有,请看上一篇)
    int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>>)) ?
               MAXIMUM_CAPACITY :
               tableSizeFor(initialCapacity + (initialCapacity >>>) + 1));
    // 初始化
    this.sizeCtl = cap;
}

ConcurrentHashMap(Map<? extends K, ? extends V> m)构造方法

 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
    this.sizeCtl = DEFAULT_CAPACITY;
    // 将集合m的元素全部放入
    putAll(m);
}

public void putAll(Map<? extends K, ? extends V> m) {
   tryPresize(m.size());
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
    	//这个是核心方法
        putVal(e.getKey(), e.getValue(), false);
}
 final V putVal(K key, V value, boolean onlyIfAbsent) {
 	// 键或值为空,抛出异常
    if (key == null || value == null) throw new NullPointerException();
    // 键的hash值经过计算获得hash值
    int hash = spread(key.hashCode());
    int binCount =;
    for (Node<K,V>[] tab = table;;) { // 无限循环
        Node<K,V> f; int n, i, fh;
        if (tab == null || (n = tab.length) ==) // 表为空或者表的长度为0
            // 初始化表
            tab = initTable();
        else if ((f = tabAt(tab, i = (n -) & hash)) == null) { // 表不为空并且表的长度大于0,并且该桶不为空
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null))) // 比较并且交换值,如tab的第i项为空则用新生成的node替换
                break;                   // no lock when adding to empty bin
        }
        else if ((fh = f.hash) == MOVED) // 该结点的hash值为MOVED
            // 进行结点的转移(在扩容的过程中)
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            synchronized (f) { // 加锁同步
                if (tabAt(tab, i) == f) { // 找到table表下标为i的节点
                    if (fh >=) { // 该table表中该结点的hash值大于0
                        // binCount赋值为
                        binCount =;
                        for (Node<K,V> e = f;; ++binCount) { // 无限循环
                            K ek;
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) { // 结点的hash值相等并且key也相等
                                // 保存该结点的val值
                                oldVal = e.val;
                                if (!onlyIfAbsent) // 进行判断
                                    // 将指定的value保存至结点,即进行了结点值的更新
                                    e.val = value;
                                break;
                            }
                            // 保存当前结点
                            Node<K,V> pred = e;
                            if ((e = e.next) == null) { // 当前结点的下一个结点为空,即为最后一个结点
                                // 新生一个结点并且赋值给next域
                                pred.next = new Node<K,V>(hash, key,
                                                          value, null);
                                // 退出循环
                                break;
                            }
                        }
                    }
                    else if (f instanceof TreeBin) { // 结点为红黑树结点类型
                        Node<K,V> p;
                        // binCount赋值为
                        binCount =;
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) { // 将hash、key、value放入红黑树
                            // 保存结点的val
                            oldVal = p.val;
                            if (!onlyIfAbsent) // 判断
                                // 赋值结点value值
                                p.val = value;
                        }
                    }
                }
            }
            if (binCount !=) { // binCount不为0
                if (binCount >= TREEIFY_THRESHOLD) // 如果binCount大于等于转化为红黑树的阈值
                    // 进行转化
                    treeifyBin(tab, i);
                if (oldVal != null) // 旧值不为空
                    // 返回旧值
                    return oldVal;
                break;
            }
        }
    }
    // 增加binCount的数量
    addCount(L, binCount);
    return null;
}

private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    // 无限循环
    while ((tab = table) == null || tab.length ==) { 
    	
        if ((sc = sizeCtl) <) 
            Thread.yield(); // lost initialization race; just spin
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -)) { // 比较sizeCtl的值与sc是否相等,相等则用-1替换
            try {
                if ((tab = table) == null || tab.length ==) { // table表为空或者大小为0
                    // sc的值是否大于,若是,则n为sc,否则,n为默认初始容量
                    int n = (sc >) ? sc : DEFAULT_CAPACITY;
                    @SuppressWarnings("unchecked")
                    // 新生结点数组
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    // 赋值给table
                    table = tab = nt;
                    // sc为n */4
                    sc = n - (n >>>);
                }
            } finally {
                // 设置sizeCtl的值
                sizeCtl = sc;
            }
            break;
        }
    }
    // 返回table
    return tab;
}

在ConcurrentHashMap中通过原子操作查找元素、替换元素和设置元素。这些原子操作起着非常关键的作用。

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

static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                    Node<K,V> c, Node<K,V> v) {
    return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}

static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
    U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}

ConcurrentHashMap(int initialCapacity, float loadFactor)构造方法该构造函数用于创建一个带有指定初始容量、加载因子和默认 concurrencyLevel (1) 的新的空映射

 public ConcurrentHashMap(int initialCapacity, float loadFactor) {
    this(initialCapacity, loadFactor,);
}

ConcurrentHashMap(int initialCapacity,float loadFactor, int concurrencyLevel)构造方法

 public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
    // 合法性判断
    if (!(loadFactor >.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
        throw new IllegalArgumentException();
    if (initialCapacity < concurrencyLevel)   // Use at least as many bins
        initialCapacity = concurrencyLevel;   // as estimated threads
    long size = (long)(.0 + (long)initialCapacity / loadFactor);
    int cap = (size >= (long)MAXIMUM_CAPACITY) ?
        MAXIMUM_CAPACITY : tableSizeFor((int)size);
    this.sizeCtl = cap;
}
  1. put(K key, V value)方法
  2. ConcurrentHashMap的键和值都不能为null
 public V put(K key, V value) {
	//还是调用putVal()方法   上面有解释
    return putVal(key, value, false);
}
  1. get(Object key)方法
 public V get(Object key) {
    Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
    // 计算key的hash值
    int h = spread(key.hashCode()); 
    if ((tab = table) != null && (n = tab.length) > &&
        (e = tabAt(tab, (n -) & h)) != null) { // 表不为空并且表的长度大于0并且key所在的桶不为空
        if ((eh = e.hash) == h) { // 表中的元素的hash值与key的hash值相等
            if ((ek = e.key) == key || (ek != null && key.equals(ek))) // 键相等
                // 返回值
                return e.val;
        }
        else if (eh <) // 结点hash值小于0
            // 在桶(链表/红黑树)中查找
            return (p = e.find(h, key)) != null ? p.val : null;
        while ((e = e.next) != null) { // 对于结点hash值大于的情况
            if (e.hash == h &&
                ((ek = e.key) == key || (ek != null && key.equals(ek))))
                return e.val;
        }
    }
    return null;
}

总结:

ConcurrentHashMap和Hashtable的区别 ConcurrentHashMap和Hashtable的区别主要体现在实现线程的安全的方式上不同。 底层数据结构 :JDK1.7的ConcurrentHashMap底层采用分段的数组+链表实现,JDK1.8采用的数 据结构跟HashMapl.8的结构一样,数组+链表/红黑二叉树。Hashtable和JDK1.8之前的HashMap 的底层数据结构类似都是采用数组+链表的形式,数组是HashMap的主体,链表则是主要为了解决 哈希冲突而存在的; 实现线程安全的方式 :①在JDK1.7的时候,ConcurrentHashMap (分段锁)对整个桶数 组进行了分割分段(Segment),每一把锁只锁容器其中一部分数据,多线程访问容器里不同数据段的 数据,就不会存在锁竞争,提高并发访问率。到了 JDK1.8的时候已经摒弃了Segment的概念,而是直接用Node数组+链表+红黑树的数据结构来实现,并发控制使用synchronized和CAS来操作。(JDK1.6以后对synchronized锁做了很多优化)整个看起来就像是优化过且线程安全的HashMap,虽然在IDK1.8中还能看到Segment的数据结构,但是已经简化了属性,只是为了兼容旧版本;②Hashtable(同一把锁):使用synchronized来保证线程安全,效率非常低下。当一个线程访问同步方法时,其他线程也访问同步方法,可能会进入阻塞或轮询状态,如使用put添加元素,另一个线程不能使用put添加元素,也不能使用get,竞争会越来越激烈效率越低。Hashtable是遗留类,很多映射的常用功能与HashMap类似,不同的是它承自Dictionary类,并且是线程安全的,任一时间只有一个线程能写Hashtable,并发性不如ConcurrentHashMap,因为ConcurrentHashMap引入了分段锁。Hashtable不建议在新代码中使用,不需要线程安全的场合可以用HashMap替换,需要线程安全的场合可以用ConcurrentHashMap替换。