简单聊聊HashMap
[TOC]
1 HashMap为什么线程不安全?
对于大部分公司来说:java8已经能够满足业务需求,同时以稳定性为主,不轻易升级版本。
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) */ 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; }
底层实现:数组加链表
首先通过hashcode()函数计算出hash值,然后取余得到下标,当hash冲突的时候1.7采用的是头插法,头插法速度快一些,不需要遍历到尾节点,这时候get的时候就不能取得头插法的元素,因为你的头结点是周瑜,所以这里就必须每次插入之后移动链表
分析源码:首先看构造方法,无参,指定数组容量,总的属性16*0.75=12;
public static int highestOneBit(int i) { return i & (MIN_VALUE >>> numberOfLeadingZeros(i)); } public static int numberOfLeadingZeros(int i) { // HD, Count leading 0's if (i <= 0) return i == 0 ? 32 : 0; int n = 31; if (i >= 1 << 16) { n -= 16; i >>>= 16; } if (i >= 1 << 8) { n -= 8; i >>>= 8; } if (i >= 1 << 4) { n -= 4; i >>>= 4; } if (i >= 1 << 2) { n -= 2; i >>>= 2; } return n - (i >>> 1); }
8421 先翻译成二进制数,有一个位数为一,其他都不为一 0000 0101 代表10 put和get环环相扣的,必须是2的N次幂,才能通过-1加上与运算得到小于length的下标,配套使用 不管高四位怎么变,最终的结果的都不会变,但是int类型很多不一样,所以就会有冲突,影响get的元素,遍历比较慢 右移且进行了异或运算的原因,提高返回来的hashcode的散列性,
扩容的目的就是提高搜索效率
长链表变成短链表
头插法1,2,3扩容之后变成3,2,1
单线程的会怎么样?扩容resize()两个线程都会newTable公用
调用Put的时候,多线程扩容的时候会导致循环链表,因为可以会阻塞
记得先看构造函数,看各种方法,一层层往里面挖
记得看注释说明
熟悉数据结构与算法看源码会简单很多
代码量膨胀了一倍来解决这些问题
数组+链表/红黑树
扩容时插入顺序的改进
函数方法 forEach compute系列
Map新的API merge replace
java 7 中经典的哈希表实现
存在的问题:非常容易碰到死锁,潜在的安全隐患
Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds.
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的时候,不需要计算hash,只需要看原来的hash值新增的bit是1还是0,是0的话索引不变,是1的话变成“原索引+旧容量”,正是这样巧妙地rehash方式,即省去了重新计算hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,均匀地分散冲突的节点到新的桶中