面试常见问题

1、你看过那些源码吗?
2、那你能讲讲HashMap的实现原理吗?
3、HashMap什么时候会进行rehash?
4、HashMap什么时候会进行扩容?
5、那HashMap的初始容量设置成多少比较合适呢?
6、结合源码说说HashMap在高并发场景中为什么会出现死循环?
7、JDK1.8中对HashMap做了哪些性能优化?
8、HashMap和HashTable有何不同?
9、HashMap 和 ConcurrentHashMap 的区别?
10、ConcurrentHashMap和LinkedHashMap有什么区别?
11、为什么ConcurrentHashMap中的链表转红黑树的阀值是8?
12、什么是ConcurrentSkipListMap?他和ConcurrentHashMap有什么区别?
13、还看过其他的源码吗?Spring的源码有了解吗?
14、SpringBoot的源码呢?知道starter是怎么实现的吗?

一、构造方法

1.1无参构造方法

默认初始化容量16,加载因子0.75

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

1.2 指定初始容量initialCapacity,默认加载因子0.75

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

1.3 指定初始容量initialCapaticy和加载因子loadFactor

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
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;
    // 阈值初始化为初始容量最小2的倍数
    this.threshold = tableSizeFor(initialCapacity);
}

HashMap初始容量为指定容量的最小2的倍数。该方法将初始容量的二进制最高位右移再与原值进行或运算,将低位全部转换为1,最后加1,由此得到初始化容量的最小的2的倍数

/**
 * Returns a power of two size for the given target capacity.
 */
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;
}

1.4 用其他Map初始化

/**
 * Constructs a new <tt>HashMap</tt> with the same mappings as the
 * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 * default load factor (0.75) and an initial capacity sufficient to
 * hold the mappings in the specified <tt>Map</tt>.
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

二、属性解析

2.1 基本属性

/**
 * 默认初始化容量,必须是2的倍数,初始默认为16
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * 最大容量,小于2的30次方
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认加载因子0.75
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 列表转红黑树的阈值,列表大于等于8时将转为红黑树
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * 红黑树转列表的阈值
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * 列表转红黑树的最小容量,如果一个槽中的数据太多,HashMap应考虑扩容,该值用来解决扩容与列表转树的冲突
 */
static final int MIN_TREEIFY_CAPACITY = 64;

/**
 * 在首次使用时初始化,根据需要扩容,大小始终为2的倍数
 */
transient Node<K,V>[] table;

/**
 * Holds cached entrySet(). Note that AbstractMap fields are used
 * for keySet() and values().
 */
transient Set<Map.Entry<K,V>> entrySet;

/**
 * HashMap中键值对的数量
 */
transient int size;

/**
 * HashMap结构修改次数
 */
transient int modCount;

/**
 * 下次扩容时table的大小
 * @serial
 */
int threshold;

/**
 * hash table 加载因子
 * @serial
 */
final float loadFactor;

2.2 内部类Node<K,V>

/**
 * 基础hash节点,包含一个hash值,一个key-value键值对,和下个节点
 */
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

2.3 内部类TreeNode<K,V>

/**
 * 红黑树节点,包含父节点、左节点、右节点、前置节点以及节点颜色
 */
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);
    }

    /**
     * Returns root of tree containing this node.
     */
    final TreeNode<K,V> root() {
        for (TreeNode<K,V> r = this, p;;) {
            if ((p = r.parent) == null)
                return r;
            r = p;
        }
    }
    ......
}

三、主要方法解析

3.1 hash(Object key)

/**
 * key首先经过原生的hash方法后返回int类型的hash值,将该值的高16位右移传递到低16位并与原来的值异或运算。
 * 这样处理是为了将key的hash值的高位特征传递到低位,降低hash冲突的概率。
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

3.2 put(K key, V value)

/**
 * 在map中将指定的键和值进行关联映射,如果map中已经存在该键的映射关系,
 * 那么map中该键关联的值将被替换。
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return 返回key关联的旧值,如果原来key关联的为null,则返回null
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; 
    Node<K,V> p; 
    int n, i;
    // talbe在第一次使用时初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // key的hash值未产生hash冲突,则将value作为第一个节点存储到map中
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; 
        K k;
        // 出现hash冲突,且key与第一个节点相同,用节点e标记该节点
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // key所对应的槽中的第一个节点为TreeNode
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 出现hash冲突后,遍历列表
            for (int binCount = 0; ; ++binCount) {
                // 遍历列表,如无重复key值,将value值添加到列表末尾
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 如果列表长度大于等于阈值8,则将列表转换为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 如果列表中存在重复的key,用节点e标记已存在的节点
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 已存在key的映射
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            // onlyIfAbsent为false或旧值为null,将新的value映射到map中
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            // 
            afterNodeAccess(e);
            // 返回key关联的旧值
            return oldValue;
        }
    }
    ++modCount;
    // map中数据量大于容量阈值(容量*加载因子),map进行扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

3.3 resize()

/**
 * 初始化或扩容(2倍),  如果为null,则按照初始容量分配,否则以2的倍数进行扩容。
 * @return the table
 */
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) {
        // 如果未超过容量最大值,则扩容2倍
        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
        // 初始容量值为0,初始化时容量为默认大小16
        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) {
        // 进行rehash,把数据转移的扩容后的HashMap中
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // hash槽中只有一个元素时,直接转移过去
                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;
                        // HashMap槽中的数据为列表时,由于HashMap扩容后容量变为原来的两倍,通                             // 过 `e.hash & oldCap` 运算,如果结果等于0, 则表示当前元素在新                                 // table中位置与原来相同,如果不等于0,则在新table中位置需要增加原来的                             // 容量oldCap
                        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;
}

3.4 treeifyBin(Node<K,V>[] tab, int hash)

/**
 * 将列表转红黑树
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; 
    Node<K,V> e;
    // 如果数组为null或数组容量小于列表转红黑树的阈值(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);
    }
}

四、多线程下HashMap死循环问题分析

HashMap多线程下死循环问题在JDK1.7存在,JDK1.8已经解决了死循环的问题,但仍然不是线程安全的。

JDK1.7多线程下死循环代码分析

/**
 * Rehashes the contents of this map into a new array with a
 * larger capacity.  This method is called automatically when the
 * number of keys in this map reaches its threshold.
 *
 * If current capacity is MAXIMUM_CAPACITY, this method does not
 * resize the map, but sets threshold to Integer.MAX_VALUE.
 * This has the effect of preventing future calls.
 *
 * @param newCapacity the new capacity, MUST be a power of two;
 *        must be greater than current capacity unless current
 *        capacity is MAXIMUM_CAPACITY (in which case value
 *        is irrelevant).
 */
void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

/**
 * Transfers all entries from current table to newTable.
 */
void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next;
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}

上述代码在多线程下出现死循环的地方在transfer方法的内的do-while循环内,假设线程1在执行do-while循环的第2行代码时被挂起,此时线程1的记录了e节点信息和e.next节点信息,如果此时另外一个线程完成了整个扩容操作,此时线程1再次执行,由于线程2在执行扩容时,列表按照头插法的方式插入,线程1记录的仍是原列表的顺序,线程1继续操作,会导致列表首位相连,从而产生死循环。

此外,HashMap在多线程环境下还可能导致put操作导致元素丢失。

死循环产生的具体过程可参考:[深入理解JAVA集合系列三:HashMap的死循环解读]

五、总结

  • HashMap底层基于数组和列表来实现的,将key经过hash散列再按数组长度取模运算,定位到一个hash槽,将key-value值作为一个节点存储到hash槽中,如果槽中出现hash冲突,则以列表的形式存储节点,当列表长度大于等于8时且map中总结点个数大于等于64时,则将列表转换为红黑树。
  • 当HashMap中的节点个数超过容量阈值(容量*加载因子)时,HashMap会进行扩容,扩容是会进行rehash。
  • 当HashMap中某个槽中的元素个数大于等于8且总元素个数小于64时,这时候HashMap会进行扩容而不是转为红黑树。
  • HashMap的初始容量设置成initialCapacity = (需要存储的元素个数 / 负载因子) + 1,如果不确定,设置为16(默认值)。
  • 在JDK1.8中,当HashMap某个槽中的元素个数大于等于8时,且总元素个数超过64,则将列表转化为红黑树提高查找速度。