HashMap和ConcurrentHashMap

123 阅读4分钟

Map

Map 里面存储的都是 Entry

public interface Map<K,V> {

    V get(Object key);

    V put(K key, V value);
    

    interface Entry<K,V> {
        
        K getKey();

        V getValue();
    }

}

HashMap

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    # 容器,里面存放的是Node
    transient Node<K,V>[] table;
    # 数组扩容的阈值
    int threshold;
    # 装载因子
    final float loadFactor;
    # 所有数据的大小
    transient int size;

    # 存储 key的集合
    transient Set<K>        keySet;
    # 存储所有values
    transient Collection<V> values;
    # 存储所有 Node节点集合
    transient Set<Map.Entry<K,V>> entrySet;


    # 存放的Node,一个单项链表
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }
    # 当链表长度超过8的时候变成 TreeNode结构
    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;
    }
}

HashMap的put 和get

# put 方法会对key进行一次扰动函数的操作
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
# 扰动函数是把一个 int 类型的高16位和低16位进行异或操作,让分配的更平均
异或的操作的0 1 概率是百分50,而与和或都是百分75
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
# onlyIfAbsent 参数表示如果是true,如果key一样的话,新value不会覆盖原来value
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    # 第一次put的时候如果为空要第一次resize
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
        # hash & (n-1) 是根据table长度取模的意思
    if ((p = tab[i = (n - 1) & hash]) == null)
        # 如果算出来的下标还没有数据,直接放进去
        tab[i] = newNode(hash, key, value, null);
    else {
    # 哈希冲突了
        Node<K,V> e; K k;
        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 {
        # hash冲突但是不是第一个数据,需要往后查找
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        # 链表长度超过8,并且整个table的长度要小于64就转换为红黑树
                        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;
}

简图,没有画出红黑树的情况 image.png

HashMap 的 reSize

如果整个map里面的entry超过了 threshold 就会触发resize,还有一个条件,在转换为红黑树的时候,如果tablesize小于64,那么也会触发扩容


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;
        }
        # 扩容为原来的两倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        # 第一次初始化扩容 容量是16 阈值是 12
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 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;
}

如果元素数量超过了阈值就会让 tableSize 和阈值扩容为原来的两倍. 通过扩容逻辑可以推理出来, 容器一定有很多空位,因为阈值小于容器,元素超过阈值,容器就要扩容 image.png

HashMap对entrySet的维护

HashMap对entrySet维护的思想是创建一个自定义迭代器 EntryIterator 对整个容器进行 从下往上,从头到尾 的遍历. 并不是真的维护了一个 Set在添加的时候额外复制一份数据.


    # 我们调用 entrySet方法的时候是创建了一个 EntrySet 对象
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
    # 当我们遍历entrySet 的时候使用的是 EntryIterator 迭代器
    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
    }

    # entrySet的父类抽象
    abstract class HashIterator {
        # 链表指向的下一个数据
        Node<K,V> next;        // next entry to return
        # 当前桶的链表数据
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        # 指向hashmap 的容器数组的下标
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            # 这个操作是让index指向有数据的槽,并且让next指向槽内第一个位置
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }
        # entrySet 的 迭代器 的next方法调用的方法
        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;
        }

效果图如下

image.png

ConCurrentHashMap jdk1.8

JDK1.8 的ConcurrentHashMap 大体上和 HashMap差不多,就是在并发上做了手脚,我们来看一下put就可以了

image.png