HashMap随笔记录
HashMap
1、是应用更广泛的哈希表
实现
2、jdk1.7中底层是由数组(也有叫做“位桶”的)+链表实现;jdk1.8中底层是由数组+链表/红黑树实现
3、可以存储null键和null值,线程不安全
4、初始size为16,扩容:newsize = oldsize*2,size一定为2的n次幂
5、扩容针对整个Map,每次扩容时,原来数组中的元素依次重新计算存放位置,并重新插入
6、插入元素后才判断该不该扩容,有可能无效扩容(插入后如果扩容,如果没有再次插入,就会产生无效扩容)
7、当Map中元素总数超过Entry数组的75%,触发扩容操作,为了减少链表长度,元素分配更均匀
8、1.7中是先扩容后插入新值的,1.8中是先插值再扩容
为什么说HashMap是线程不安全的?
在接近临界点时,若此时两个或者多个线程进行put操作,都会进行resize(扩容)和reHash(为key重新计算所在位置),而reHash在并发的情况下可能会形成链表环
。
总结来说就是在多线程环境下,使用HashMap进行put操作会引起死循环,导致CPU利用率接近100%,所以在并发情况下不能使用HashMap。
为什么在并发执行put操作会引起死循环?
是因为多线程会导致HashMap的Entry链表形成环形数据结构,一旦形成环形数据结构,Entry的next节点永远不为空,就会产生死循环获取Entry。
jdk1.7的情况下,并发扩容时容易形成链表环,此情况在1.8时就好太多太多了。因为在1.8中当链表长度大于阈值(默认长度为8)时,链表会被改成树形(红黑树)结构。
jdk1.7中HashMap的实现
HashMap底层维护的是数组+链表,我们可以通过一小段源码来看看:
1 /** 2 * The default initial capacity - MUST be a power of two. 3 * 即 默认初始大小,值为16 4 */ 5 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 6 7 /** 8 * The maximum capacity, used if a higher value is implicitly specified 9 * by either of the constructors with arguments. 10 * MUST be a power of two <= 1<<30. 11 * 即 最大容量,必须为2^30 12 */ 13 static final int MAXIMUM_CAPACITY = 1 << 30; 14 15 /** 16 * The load factor used when none specified in constructor. 17 * 负载因子为0.75 18 */ 19 static final float DEFAULT_LOAD_FACTOR = 0.75f; 20 21 /** 22 * The bin count threshold for using a tree rather than list for a 23 * bin. Bins are converted to trees when adding an element to a 24 * bin with at least this many nodes. The value must be greater 25 * than 2 and should be at least 8 to mesh with assumptions in 26 * tree removal about conversion back to plain bins upon 27 * shrinkage. 28 * 大致意思就是说hash冲突默认采用单链表存储,当单链表节点个数大于8时,会转化为红黑树存储 29 */ 30 static final int TREEIFY_THRESHOLD = 8; 31 32 /** 33 * The bin count threshold for untreeifying a (split) bin during a 34 * resize operation. Should be less than TREEIFY_THRESHOLD, and at 35 * most 6 to mesh with shrinkage detection under removal. 36 * hash冲突默认采用单链表存储,当单链表节点个数大于8时,会转化 37 为红黑树存储。 38 * 当红黑树中节点少于6时,则转化为单链表存储 39 */ 40 static final int UNTREEIFY_THRESHOLD = 6; 41 42 /** 43 * The smallest table capacity for which bins may be treeified. 44 * (Otherwise the table is resized if too many nodes in a bin.) 45 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts 46 * between resizing and treeification thresholds. 47 * hash冲突默认采用单链表存储,当单链表节点个数大于8时,会转化为红黑树存储。 48 * 但是有一个前提:要求数组长度大于64,否则不会进行转化 49 */ 50 static final int MIN_TREEIFY_CAPACITY = 64;
通过以上代码可以看出初始容量(16)、负载因子以及对数组的说明。
数组中的每一个元素其实就是Entry<K,V>[] table,Map中的key和value就是以Entry的形式存储的。
Entry包含四个属性:key、value、hash值和用于单向链表的next。关于Entry<K,V>的具体定义参看如下源码:
1 static class Entry<K,V> implements Map.Entry<K,V> { 2 final K key; 3 V value; 4 Entry<K,V> next; 5 int hash; 6 7 Entry(int h, K k, V v, Entry<K,V> n) { 8 value = v; 9 next = n; 10 key = k; 11 hash = h; 12 } 13 14 public final K getKey() { 15 return key; 16 } 17 18 public final V getValue() { 19 return value; 20 } 21 22 public final V setValue(V newValue) { 23 V oldValue = value; 24 value = newValue; 25 return oldValue; 26 } 27 28 public final boolean equals(Object o) { 29 if (!(o instanceof Map.Entry)) 30 return false; 31 Map.Entry e = (Map.Entry)o; 32 Object k1 = getKey(); 33 Object k2 = e.getKey(); 34 if (k1 == k2 || (k1 != null && k1.equals(k2))) { 35 Object v1 = getValue(); 36 Object v2 = e.getValue(); 37 if (v1 == v2 || (v1 != null && v1.equals(v2))) 38 return true; 39 } 40 return false; 41 } 42 43 public final int hashCode() { 44 return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); 45 } 46 47 public final String toString() { 48 return getKey() + "=" + getValue(); 49 } 50 51 /** 52 * This method is invoked whenever the value in an entry is 53 * overwritten by an invocation of put(k,v) for a key k that's already 54 * in the HashMap. 55 */ 56 void recordAccess(HashMap<K,V> m) { 57 } 58 59 /** 60 * This method is invoked whenever the entry is 61 * removed from the table. 62 */ 63 void recordRemoval(HashMap<K,V> m) { 64 } 65 }
HashMap的初始值要考虑加载因子:
- 哈希冲突:若干Key的哈希值按数组大小取模后,如果落在同一个数组下标上,将组成一条Entry链,对Key的查找需要遍历Entry链上的每个元素执行equals()比较。
- 加载因子:为了降低哈希冲突的概率,默认当HashMap中的键值对达到数组大小的75%时,即会触发扩容。因此,如果预估容量是100,即需要设定100/0.75=134的数组大小。
- 空间换时间:如果希望加快Key查找的时间,还可以进一步降低加载因子,加大初始大小,以降低哈希冲突的概率。
jdk1.8中HashMap的实现
transient Node<K,V>[] table;
Entry的名字变成了Node,原因是和红黑树的实现TreeNode相关联。1.8与1.7最大的不同就是利用了红黑树,即由数组+链表(或红黑树)组成
在jdk1.8中,如果链表长度大于8且节点数组长度大于64的时候
,就把链表下所有的节点转为红黑树。
可以看下put方法源码:
1 static final int TREEIFY_THRESHOLD = 8;
2
3 public V put(K key, V value) {
4 return putVal(hash(key), key, value, false, true);
5 }
6
7
8 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
9 boolean evict) {
10 Node<K,V>[] tab;
11 Node<K,V> p;
12 int n, i;
13 //如果当前map中无数据,执行resize方法。并且返回n
14 if ((tab = table) == null || (n = tab.length) == 0)
15 n = (tab = resize()).length;
16 //如果要插入的键值对要存放的这个位置刚好没有元素,那么把他封装成Node对象,放在这个位置上即可
17 if ((p = tab[i = (n - 1) & hash]) == null)
18 tab[i] = newNode(hash, key, value, null);
19 //否则的话,说明这上面有元素
20 else {
21 Node<K,V> e; K k;
22 //如果这个元素的key与要插入的一样,那么就替换一下。
23 if (p.hash == hash &&
24 ((k = p.key) == key || (key != null && key.equals(k))))
25 e = p;
26 //1.如果当前节点是TreeNode类型的数据,执行putTreeVal方法
27 else if (p instanceof TreeNode)
28 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
29 else {
30 //还是遍历这条链子上的数据,跟jdk7没什么区别
31 for (int binCount = 0; ; ++binCount) {
32 if ((e = p.next) == null) {
33 p.next = newNode(hash, key, value, null);
34 //2.完成了操作后多做了一件事情,判断,并且可能执行treeifyBin方法
35 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin()
就是将链表转换成红黑树。
36 treeifyBin(tab, hash);
37 break;
38 }
39 if (e.hash == hash &&
40 ((k = e.key) == key || (key != null && key.equals(k))))
41 break;
42 p = e;
43 }
44 }
45 if (e != null) { // existing mapping for key
46 V oldValue = e.value;
47 if (!onlyIfAbsent || oldValue == null) //true || --
48 e.value = value;
49 //3.
50 afterNodeAccess(e);
51 return oldValue;
52 }
53 }
54 ++modCount;
55 //判断阈值,决定是否扩容
56 if (++size > threshold)
57 resize();
58 //4.
59 afterNodeInsertion(evict);
60 return null;
61 }
树化操作的过程有点复杂,可以结合源码来看看。将原本的单链表转化为双向链表,再遍历这个双向链表转化为红黑树
。
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;//hd指向首节点,tl指向尾节点 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); // 继续遍历单链表 //将原本的单链表转化为一个节点类型为TreeNode的双向链表 if ((tab[index] = hd) != null) // 把转换后的双向链表,替换数组原来位置上的单向链表 hd.treeify(tab); // 将当前双向链表树形化 } }
大家要特别注意一点,树化有个要求就是数组长度必须大于等于MIN_TREEIFY_CAPACITY(64),否则继续采用扩容策略。
将双向链表转化为红黑树的实现:
final void treeify(Node<K,V>[] tab) { TreeNode<K,V> root = null; // 定义红黑树的根节点 for (TreeNode<K,V> x = this, next; x != null; x = next) { // 从TreeNode双向链表的头节点开始逐个遍历 next = (TreeNode<K,V>)x.next; // 头节点的后继节点 x.left = x.right = null; if (root == null) { x.parent = null; x.red = false; root = x; // 头节点作为红黑树的根,设置为黑色 } else { // 红黑树存在根节点 K k = x.key; int h = x.hash; Class<?> kc = null; for (TreeNode<K,V> p = root;;) { // 从根开始遍历整个红黑树 int dir, ph; K pk = p.key; if ((ph = p.hash) > h) // 当前红黑树节点p的hash值大于双向链表节点x的哈希值 dir = -1; else if (ph < h) // 当前红黑树节点的hash值小于双向链表节点x的哈希值 dir = 1; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) // 当前红黑树节点的hash值等于双向链表节点x的哈希值,则如果key值采用比较器一致则比较key值 dir = tieBreakOrder(k, pk); //如果key值也一致则比较className和identityHashCode TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { // 如果当前红黑树节点p是叶子节点,那么双向链表节点x就找到了插入的位置 x.parent = xp; if (dir <= 0) //根据dir的值,插入到p的左孩子或者右孩子 xp.left = x; else xp.right = x; root = balanceInsertion(root, x); //红黑树中插入元素,需要进行平衡调整(过程和TreeMap调整逻辑一模一样) break; } } } } //将TreeNode双向链表转化为红黑树结构之后,由于红黑树是基于根节点进行查找,所以必须将红黑树的根节点作为数组当前位置的元素 moveRootToFront(tab, root); }
然后将红黑树的根节点移动端数组的索引所在位置上:
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) { int n; if (root != null && tab != null && (n = tab.length) > 0) { int index = (n - 1) & root.hash; //找到红黑树根节点在数组中的位置 TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; //获取当前数组中该位置的元素 if (root != first) { //红黑树根节点不是数组当前位置的元素 Node<K,V> rn; tab[index] = root; TreeNode<K,V> rp = root.prev; if ((rn = root.next) != null) //将红黑树根节点前后节点相连 ((TreeNode<K,V>)rn).prev = rp; if (rp != null) rp.next = rn; if (first != null) //将数组当前位置的元素,作为红黑树根节点的后继节点 first.prev = root; root.next = first; root.prev = null; } assert checkInvariants(root); } }