Map

01 / HashMap

在JDK8中,HashMap底层采用“数组+链表+红黑树”实现。在学习HashMap原理时,我们应当重点关注它的数据结构、put的过程、以及扩容机制。

源码解读:

数据结构:

初始的时候一定是数组+链表,到一定规模的时候转为树。

树节点继承链表节点,在数据结构为树时保留了链表的特征,当由树转为链表时,非常容易。

transient Node<K,V>[] table;//Node类型的数组(数组里面的每个节点可以是一个单向链表)
//Node节点,单链表
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    。。。
}
//树的结构(TreeNode间接继承了Node)
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
}

1.1 put()的过程

1.若数组为空,则初次扩容。

2.数组第i个位置的头节点为空(链表不存在),则新建链表节点。

3.数组第i个位置的头节点非空(已经存在链表或树),则将元素插入槽。

  • 若元素等于头节点(key),则直接覆盖;
  • 若元素为树型节点,则添加到树;
  • 若元素为链表节点,并且链表长度小于8,则添加至链表; .
  • 若元素为链表节点,并且链表长度达到8,则扩容或转为树,再添加元素;

4.若元素的个数超过阈值,则再次扩容。

源码解读:

public V put(K key, V value) {
    //先算一下key的hash值对数组取模作为下标
        return putVal(hash(key), key, value, false, true);
    }
//计算哈希值
static final int hash(Object key) {
        int h;
    //先取key的hashCode()再异或上hashCode之后的结果右移16位的值
    //高位与低位做异或运算,降低碰撞的几率
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
     //1、数组为空
        if ((tab = table) == null || (n = tab.length) == 0)
            //初次扩容
            n = (tab = resize()).length;
     //计算元素的位置(hash函数与数组长度与运算),获取头节点为空时
        if ((p = tab[i = (n - 1) & hash]) == null)
            //创建链表节点
            tab[i] = newNode(hash, key, value, null);
        else {//当数组和头节点都不为空
            Node<K,V> e; K k;
            //如果传入的key和头节点是相等的
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //覆盖
                e = p;
            else if (p instanceof TreeNode)//如果头结点是树
                //将元素添加到树里面去
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//既不是头节点,又不是树,那就是链表
                for (int binCount = 0; ; ++binCount) {
                    //如果头结点的后继节点位空
                    if ((e = p.next) == null) {
                        //新建一个节点插到链表后面
                        p.next = newNode(hash, key, value, null);
                        //将数据插入之后,查看长度是不是大于等于8-1
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //转为树(里面会做判断是扩容还是转为树)
                            treeifyBin(tab, hash);
                        break;
                    }
                    //遍历时发现有个元素等于当前元素(即已存在节点)
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //处理节点的值,以上是处理节点的位置
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //允许更新已存在的值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//更新结点的值
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//增加修改数量
        if (++size > threshold)//数组规模是不是大于阈值
            resize();//扩容
        afterNodeInsertion(evict);
        return null;
    }

当链表的长度达到8时,要先判断一下数组的长度是否大于64,大于就转为树,小于先扩容

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    //判断数组长度和64大小
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();//扩容
    //将链表转为树
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

hashCode():用来判断放在那个位置

static final int TREEIFY_THRESHOLD = 8;
static final int MIN_TREEIFY_CAPACITY = 64;

1.2扩容机制

默认容量16,每次扩容时将容量翻倍,容量一定是2的n次方
16 = 00010000, 32 = 00100000
hash & (16-1) = hash & 00001111
hash & (32-1) = hash & 00011111
翻倍扩容后,计算的索引值多出一位,
若该位为0则位置不变,否则位置+16。

java map 总和_java map 总和

数据位置搬过去怎么办?再次计算?不!节点要么在原来的槽里,还是在原有槽+16的位置(前十六位低位槽,后16高位槽)

源码解读:

int threshold;  //人为指定的容量
final float loadFactor; //负载因子 默认值0.75

//构造器
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

//负载因子 默认值0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;

//指定容量的构造器
 public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
//
 public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor; //初始化负载因子
        this.threshold = tableSizeFor(initialCapacity);//初始化容量做处理
    }

//将人为指定的容量计算转为接近的2的n次方
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

扩容源码:

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        //判断旧的容量是不是超过最大值
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //没有达到最大容量时,新的容量是旧的容量的2倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //旧的threshold
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        //给一个默认容量16
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {//指定容量位0时
        //临界值
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    //重新初始化新的数组,以上时双倍扩容机制,下面是迁移机制
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;//赋予新的数组
    //之前的数组不为空,遍历旧的桶
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;//清空旧桶槽
                if (e.next == null)//当前槽的头节点没有后继时
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)//如果头结点是树形
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);//添加到树里面
                else { // preserve order不是树,那就是链表
                    //低位槽的头尾节点
                    Node<K,V> loHead = null, loTail = null;
                    //高位槽的头尾节点
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    //分配槽的位置,在低位槽还是在高位槽
                    do {
                        next = e.next;
                        if ((e.hash & oldCap) == 0) {//低位槽
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        else {//高位槽
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    //前面定位好位置,下面开始搬数据
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;//低位放在原先的位置
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;//高位放在原先+翻倍容量的位置
                    }
                }
            }
        }
    }
    return newTab;
}

迁移机制中树的迁移

也是先做节点位置的分配,再将节点链接到树中

final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
    //低高位槽节点
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
    //遍历迭代
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                //next是单向链表指向下一个节点的,不是红黑树的,将树当成链表去迭代,(虽然是树,但是链表的指向关系依然保留)
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }

            if (loHead != null) {//低位非空
                //链表长度小于等于6
                if (lc <= UNTREEIFY_THRESHOLD)
                    //将树转为链表
                    tab[index] = loHead.untreeify(map);
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {//高位非空
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }
static final int UNTREEIFY_THRESHOLD = 6;//链表长度小于等于6,将树转为链表

什么时候红黑树再退化为链表?

在扩容的时候 ,将旧的数组里的某一棵树搬到新的数组时,将原红黑树拆开(一部分放在低位,一部分放在高位)后的长度小于等于6,就退化为链表

1.3查询机制

1.查询时,先定位槽,再从槽中迭代链表或树,找到对应的节点;
2.迭代时,先遍历槽,再遍历槽中的链表或树,遍历出所有节点。

源码解读:

get

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

//
final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //根据key求出头节点的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {//得到头节点

            if (first.hash == hash && // always check first node
                //判断你传入的key和头结点的key是否相等
                ((k = first.key) == key || (key != null && key.equals(k))))
                //相等就返回头节点
                return first;
            //不相等就迭代
            if ((e = first.next) != null) {
                //迭代链表
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

迭代key

public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new KeySet();
        keySet = ks;
    }
    return ks;
}

//
 final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
     //迭代器
        public final Iterator<K> iterator()     { return new KeyIterator(); }
       。。。。。。
        
    }

//具体的迭代器
final class KeyIterator extends HashIterator//继承
        implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

//父类迭代器
abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            //从头开始遍历槽
            if (t != null && size > 0) { // advance to first entry
                //找到第一个非空的槽
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

    //找下一个节点
        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        。。。。。
    }

1.4相关参数

java map 总和_java_02

并不是说链表的长度达到8,就转为树,还要看数组的长度有没有达到64

02 / TreeMap

TreeMap底层采用红黑树结构来实现,在插入元素时,需要进行比较。TreeMap通过 允许通过默认的比较器或指定的比较器对元素进行比较,这两种比较方式分别叫做自然排序和定制排序。数据结构和排序的规则,是学习TreeMap时需要重点关注的内容。

源码解读:

private transient Entry<K,V> root;//树的根节点  Entry

// Entry结构   红黑树
static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;//颜色的标识
}

比较器

private final Comparator<? super K> comparator;

//默认构造器将比较器初始化为null,才需元素自带的方法比较  自然排序
public TreeMap() {
        comparator = null;
    }

//传入你指定的构造器  定制排序
 public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

//比较规则  TreeMap的key必须实现Comparable接口!!!
final int compare(Object k1, Object k2) {
    //如果比较器为空,两个key比较,非空使用定制排序
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }

put

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        //目的利用这个方法对key做检查,key可能为null或者没实现Comparable接口
        compare(key, key); // type (and possibly null) check

        //当根节点为空,先初始化根节点
        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    int cmp;
    Entry<K,V> parent;
    // split comparator and comparable paths
    Comparator<? super K> cpr = comparator;
    if (cpr != null) {//比较器不为空,定制排序
        do {
            parent = t;
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    else {//自然排序
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        do {
            parent = t;
            cmp = k.compareTo(t.key);//利用定制比较器比较
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    Entry<K,V> e = new Entry<>(key, value, parent);
    //添加数据
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}

01 /同步集合

Collections类中提供了多个synchronizexXxx()方法,该方法可以将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题。

Collections是一个工具类,Collection是一个接口

java map 总和_链表_03

public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
    return new SynchronizedCollection<>(c);
}

 static class SynchronizedCollection<E> implements Collection<E>, Serializable {
        private static final long serialVersionUID = 3053995032091335093L;

        final Collection<E> c;  // Backing Collection
        final Object mutex;     // Object on which to synchronize

        SynchronizedCollection(Collection<E> c) {
            this.c = Objects.requireNonNull(c);
            mutex = this;
        }

        SynchronizedCollection(Collection<E> c, Object mutex) {
            this.c = Objects.requireNonNull(c);
            this.mutex = Objects.requireNonNull(mutex);
        }
     
       public int size() {
            synchronized (mutex) {return c.size();}
        }
。。。。。
 }

注意:Collection并不是把所有的方法都加锁,迭代方法没有加锁,需要自己加锁

总结:用Collections的synchronizexXxx()方法,将一个集合转为线程安全的集合,几乎所有的方法都会被加锁,但是对于Collection的迭代方法没有被加锁

02 /不变集合

Collections提供了如下三类方法来返回一个不可变的集合,这三类方法的参数是原有的集合对象,返回值是该集合的“只读"版本。通过Collections提供的三类方法,可以生 成“只读’的Collection或Map。

  • emptyxxx():返回一个空的不可变的集合对象;
  • singletonx);:返回一个只包含指定对象的不可变的集合对象;
  • unmodifiablexXxx(): 返回指定集合对象的不可变视图。

不可变了,这个时候也是线程安全的,也能解决并发线程安全问题

JUC包下的集合

简介

java map 总和_java_04

01 / CopyOnWriteArrayList

对于CopyOnWriteArrayList集合,正如它的名字所暗示的,它采用复制底层数组的方式来实现写操作。当线程对CopyOnWriteArrayList集合执行读取操作时, 线程将会直接读取集合本身,无须加锁与阻塞
当线程对CopyOnWriteArrayList集合执行写入操作时,该集合会在底层复制一份新的数组,接下来对新的数组执行写入操作。由于CopyOnWriteArraylist集合的写入操作都是对数组的副本执行操作.因此它是线程安全的。
需要指出的是,由于CopyOnWriteArrayList执行写入操作时需要频繁地复制数组,性能比较差,但由于读操作与写操作不是操作同一个数组,而且读操作也不需要加锁,因此读操作就很快、很安全。由此可见,CopyOnWriteArrayList适 合用在读取操作远远大于写入操作的场景中,例如缓存等。

源码解读:

final transient ReentrantLock lock = new ReentrantLock();//有可重入锁
private transient volatile Object[] array;//底层是数组

//默认构造器
 public CopyOnWriteArrayList() {
        setArray(new Object[0]);//初始化数组长度为0
    }
//传入一个数组,现将数组copy
public CopyOnWriteArrayList(E[] toCopyIn) {
        setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
    }

get读方法不加锁

public E get(int index) {
    return get(getArray(), index);
}
 private E get(Object[] a, int index) {
        return (E) a[index];
    }

修改操作(拷贝数组的时候要加锁)

public boolean add(E e) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        //拷贝数组
        Object[] newElements = Arrays.copyOf(elements, len + 1);
        //替换原有数组
        newElements[len] = e;
        setArray(newElements);
        return true;
    } finally {
        lock.unlock();
    }
}

迭代方法

public Iterator<E> iterator() {
    return new COWIterator<E>(getArray(), 0);
}

static final class COWIterator<E> implements ListIterator<E> {
        /** Snapshot of the array */
        private final Object[] snapshot;
        /** Index of element to be returned by subsequent call to next.  */
        private int cursor;

    //将原有数组赋值给snapshot(迭代副本)
        private COWIterator(Object[] elements, int initialCursor) {
            cursor = initialCursor;
            snapshot = elements;
        }

总结:CopyOnWriteArrayList读读,读写都不互斥(通过copy数组解决),但是写写互斥(因为在写上面加了锁)

02 / ConcurrentHashMap

JDK 7中的实现方式: .
为了提高并发度,在JDK7中, 一个HashMap被拆分为多个子HashMap。每一个子HashMap称作一 个Segment(降低锁的粒度),多个线程操作多个Segment相互独立。在JDK 7中的分段锁,有三个好处:

1.减少Hash冲突, 避免一个槽里有太多元素。

2.提高读和写的并发度,段与段之间相互独立。

3.提高了扩容的并发度,它不是整个ConcurrentHashMap- 起扩容,而是每个Segment独立扩容。

java map 总和_java map 总和_05

每个槽里存的是段,每个段存一个HashMap。

总结:即分段加锁

JDK 8中的实现方式:
JDK 8的实现有很大变化,首先是没有了分段锁,所有数据都放在-个大的HashMap中。其次是引入了红黑树。如果头节点是Node类型,则尾随它的就是-个普通的链表。如果头节点是TreeNode类型,它的后面就是一颗红 黑树,而TreeNode是Node的子类。 这种实现方式的优点是:

1.使用红黑树,当一个槽里有很多元素时,其查询和更新速度会比链表快很多,Hash冲突的问题由此得到较好的解决。
2.加锁的粒度,并非整个ConcurrentHashMap,而是对每个头节点分别加锁,即并发度,就是Node数组的长度,初始长度为16,和在JDK 7中初Segment的个数相同。

3.并发扩容,这是难度最大的。在JDK7中, -旦Segment的个数在初始化的时候确立,不能再更改,并发度被固定。之后只是在每个Segment内部扩容,这意味着每个Segment独立扩容,互不影响,不存在并发扩容的问题。但在JDK 8中,相当于只有1个Segment,当一个线程要扩容Node数组的时候,其他线程还要读写,因此处理过程很复杂。

java map 总和_数组_06

每个槽里可以存Node(链表)和TreeNode(树)

源码解读:

//两个table
transient volatile Node<K,V>[] table;//存储元素的数组
 private transient volatile Node<K,V>[] nextTable;//扩容时使用的table

private transient volatile int sizeCtl;//对初始化和扩容机制进行控制

//构造器
 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;//默认容量16
        putAll(m);
    }
//指定容量的构造器,将指定的数转为接近的2的n次方
 public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));//将容量扩展为原来的1.5倍
        this.sizeCtl = cap;
    }

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

put

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();//初始化数组
        //如果第i个位置的头节点为空
        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
        }
        //头节点非空:判断头结点的hsah值是-1(扩容时,正在往新的数组里迁移)
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);//去帮助扩容,帮助迁移数据
        else {//头节点不为空并且头节点不是正在迁移:可以存数据了
            V oldVal = null;
            synchronized (f) {//锁住头节点!!!!
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {//头结点的hash》=0(普通的Node,链表,将数加到链表里去)
                        。。。。
                            }
                        }
                    }
                    //节点是树,将数加到树上
                    else if (f instanceof TreeBin) {
                        。。。
                        }
                    }
                }
            }
            //将数加完后,判断链表长度有没有达到阈值
            if (binCount != 0) {
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    //判断数组的元素长度有没有达到阈值(3/4)
    addCount(1L, binCount);
    return null;
}

put时可能导致扩容的点:

1、 tab = helpTransfer(tab, f);//去帮助扩容,帮助迁移数据

2、 treeifyBin(tab, i);//转为树时,先看数组容量,要不要扩容

3、addCount(1L, binCount); //判断数组的元素长度有没有达到阈值(3/4)

addCount

private final void addCount(long x, int check) {
  。。。。。
                transfer(tab, null);//真正扩容的地方
            s = sumCount();
        }
    }
}

真正扩容的机制

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    int n = tab.length, stride;
    //步长,算一下每个cpu处理多少个节点
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE; // subdivide range
    //迁移前构造新的数组
    if (nextTab == null) {            // initiating
        try {
            @SuppressWarnings("unchecked")
            //新的数组扩容为2倍
            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
            nextTab = nt;
        } catch (Throwable ex) {      // try to cope with OOME
            sizeCtl = Integer.MAX_VALUE;
            return;
        }
        nextTable = nextTab;
        transferIndex = n;
    }
    int nextn = nextTab.length;
    //转发节点,查旧数组时,存新数组对应的节点
    ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
    boolean advance = true;
    boolean finishing = false; // to ensure sweep before committing nextTab
    
    for (int i = 0, bound = 0;;) {//bound是边界
        。。。
            //以CAS的方式去抢任务
            else if (U.compareAndSwapInt
                     (this, TRANSFERINDEX, nextIndex,
                      nextBound = (nextIndex > stride ?
                                   nextIndex - stride : 0))) {
                bound = nextBound;
                i = nextIndex - 1;
                advance = false;
            }
        }
        //整个集合遍历完了
        if (i < 0 || i >= n || i + n >= nextn) {
            int sc;
            if (finishing) {//转移完成
                nextTable = null;
                table = nextTab;//将老数组替换掉
                sizeCtl = (n << 1) - (n >>> 1);//从新计算,作为下次扩容的阈值
                return;
            }
            。。。。
        }
        //第i个位置为空(已经迁移完毕)
        else if ((f = tabAt(tab, i)) == null)
            advance = casTabAt(tab, i, null, fwd);//将旧的数组设置为转发节点
        else if ((fh = f.hash) == MOVED)//正在迁移
            advance = true; // already processed
        else {
            synchronized (f) {//对头结点加锁,搬数剧
                if (tabAt(tab, i) == f) {
                    Node<K,V> ln, hn;
                    if (fh >= 0) {//说明是链表,搬数剧
                        。。。。
                    }
                    else if (f instanceof TreeBin) {//说明是红黑树搬数剧
                        。。。
                    }
                }
            }
        }
    }
}

初始化数组

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,线程让步,转为就绪态
        //以CAS的方式初始化数组
        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;
                    //改变,原值的3/4,下一次扩容的关键节点
                    sc = n - (n >>> 2);
                }
            } finally {
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

ConcurrentHashMap机制小结:

  • 初始操作:以CAS方式初始化数组和头节点;
  • 插入节点:在某位置插入节点时做加锁处理;
  • 扩容操作:每个线程负责扩容一部分数据, 扩容时做加锁处理。并且扩容时依然支持读写操作,若该位置的节点不是fwd则直接读写,否则就访问访问新数组进行读写。