ConcurrentHashMap源码理解

1.ConcurrentHashMap继承关系

ConcurrentHashMap继承了AbstractMap类,同时实现了ConcurrentMap接口。

2.ConcurrentHashMap构造函数

    public ConcurrentHashMap() {
    }

    public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        this.sizeCtl = cap;
    }

    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }

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

    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        if (!(loadFactor > 0.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)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }
ConcurrentHashMap():这个没什么好说的,无参构造函数一切都是使用默认值。
ConcurrentHashMap(int):int指定了实例的初始容量,如果初始容量大于最大容量的一半,直接初始化为最大容量。否则的话,会计算参数(计算的时候已经扩大为原来的1.5倍加1),同hashmap一样,为大于计算值的最小的2的幂次方。
ConcurrentHashMap(int,float):内部实际调用了ConcurrentHashMap(int,float,int),最后一个参数填1。
ConcurrentHashMap(int,float,int):参数依次指定了实例的初始容量initialCapacity,负载因子loadFactor,同步等级concurrencyLevel。初始容量不能小于同步等级,如果小于,则令其等于同步等级的数值。然后用初始容量除以负载因子,获取数组大小,再求出最小的2的幂次方。
ConcurrentHashMap(Map):参数使用默认的参数,同时调用putAll(Map)方法。

3.ConcurrentHashMap添加元素

3.1添加元素核心类

    final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;
        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 - 1) & hash)) == null) {
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                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;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

    private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    if ((tab = table) == null || tab.length == 0) {
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

源码解析:

  1.在concurrentHashMap中要求key和value都不能为空,否则会抛出NPE。

if (key == null || value == null) throw new NullPointerException();

  2.计算key新的hash值

int hash = spread(key.hashCode());
    static final int spread(int h) {
        return (h ^ (h >>> 16)) & HASH_BITS;
    }

  3.循环实例中存放元素的table,如果table没有初始化,则进行初始化

        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();

  初始化table,这里使用了乐观锁U.compareAndSwapInt()方法,有且只有一个线程t能够将SIZECTL设置为-1,此时其他的所有线程都会进入Thread.yield()让出cpu进行循环等待。当t线程执行完成后,另一个线程t1执行乐观锁,其他线程继续循环等待,此时t1再次判断table已经不等于null,且长度也不等于0,直接执行finally中语句,并跳出循环。

  而t会一直执行下去,如果实例没有被赋予初始化容量,则使用默认的初始化容量16来作为数组长度创建数组。然后执行sc=n-(n>>>2),实际令sc=0.75sc,求出了在默认0.75f的负载因子下可存储数据数量。最后返回创建的数组node[16]。

    private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    if ((tab = table) == null || tab.length == 0) {
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

  4.

猜你喜欢

转载自www.cnblogs.com/yxth/p/10609140.html