jdk1.7也对这种情况做了处理。例如:在initHashSeedAsNeeded方法中,不使用jdk中String公开的哈希算法,而是使用其他的哈希算法来避免上述出现的问题。
final boolean initHashSeedAsNeeded(int capacity) { // 判断是否需要使用hash算法 boolean currentAltHashing = hashSeed != 0; boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); boolean switching = currentAltHashing ^ useAltHashing; if (switching) { // 初始化hash种子 hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0; } return switching; } 三、JDK1.8的HashMap源码JDK1.8中对HashMap进行了很大优化:
使用数组+链表/红黑树的数据结构,解决了底层哈希表的安全隐患;
在扩容时,通过对插入顺序的改进优化了死锁问题;
1、新增概念(1)树化的阙值
/** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */ static final int TREEIFY_THRESHOLD = 8;(2)退树化的阈值
/** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; 2、源码阅读(1)putVal()
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // 判断哈希表是否为空,为空就创建 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 如果是第一个节点,就往这个哈希桶添加一个元素 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 { // 该节点就是链表 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 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; }(2)resize:扩容方法
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 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; } 四、相关面试题分析HashMap默认容量
HashMap如何扩容
HashMap为什么是线程不安全的?
为什么HashMap的容量必须是2的n次方?1、即使你在构造函数时,不传2的n次方,在后来的初始化方法中,也会强制变成2的n次方
1.7:put => inflateTable 1.8:HashMap => tableSizeFor2、让元素能够快速定位哈希桶;让Hash表元素分布均匀,减少哈希碰撞的几率
(1)快速定位哈希桶
在哈希表实现中,有一个很重要的问题:如何将hash值映射到几个哈希桶里呢?对应java来说,就是int范围的数如何映射到哈希桶里呢?
很常见的解决方案是:取模,即int % n。但是这种方案有俩个缺点:
负数取模仍然是负数,这里要确保hash值一定是正数;
相比较HashMap的实现,这种方案性能稍微差一点;
1.7:indexFor(int h, int length){ return h & (length - 1);// 记住这行代码,java8是直接用这段代码的 }(2)为什么能让Hash表元素分布均匀,减少哈希碰撞的几率?