🌹🌹 如果您觉得我的文章对您有帮助的话,记得在 GitHub 上 star 一波哈 🌹🌹
HashMap 是线程不安全的,在多线程环境下对某个对象中 HashMap 类型的实例变量进行操作时,可能会产生各种不符合预期的问题。
本文详细说明一下 HashMap 存在的几个线程安全问题。
注:以下基于 JDK1.8
1 多线程的 put 可能导致元素的丢失
1.1 试验代码如下
注:仅作为可能会产生这个问题的样例代码,直接运行不一定会产生问题
public class ConcurrentIssueDemo1 { private static Map<String, String> map = new HashMap<>(); public static void main(String[] args) { // 线程1 => t1 new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 99999999; i++) { map.put("thread1_key" + i, "thread1_value" + i); } } }).start(); // 线程2 => t2 new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 99999999; i++) { map.put("thread2_key" + i, "thread2_value" + i); } } }).start(); } }
1.2 触发此问题的场景
先来看一下 put 方法的源码
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, I; // 初始化hash表 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 通过hash值计算在hash表中的位置,并将这个位置上的元素赋值给p,如果是空的则new一个新的node放在这个位置上 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { // hash表的当前index已经存在元素,向这个元素后追加链表 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) { // #1 p.next = newNode(hash, key, value, null); // #2 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; }
假设当前 HashMap 中的 table 状态如下:
此时 t1 和 t2 同时执行 put,假设 t1 执行 put(“key2”, “value2”),t2 执行 put(“key3”, “value3”),并且 key2 和 key3 的 hash 值与图中的 key1 相同。
那么正常情况下,put 完成后,table 的状态应该是下图二者其一
下面来看看异常情况
假设线程 1、线程 2 现在都执行到 put 源代码中#1 的位置,且当前 table 状态如下
然后两个线程都执行了 if ((e = p.next) == null)这句代码,来到了#2 这行代码。
此时假设 t1 先执行 p.next = newNode(hash, key, value, null);
那么 table 会变成如下状态
紧接着 t2 执行 p.next = newNode(hash, key, value, null);
此时 table 会变成如下状态
这样一来,key2 元素就丢了。
2 put 和 get 并发时,可能导致 get 为 null
场景:线程 1 执行 put 时,因为元素个数超出 threshold 而导致 rehash,线程 2 此时执行 get,有可能导致这个问题。
分析如下:
先看下 resize 方法源码
大致意思是,先计算新的容量和 threshold,在创建一个新 hash 表,最后将旧 hash 表中元素 rehash 到新的 hash 表中
重点代码在于#1 和#2 两句
// hash表 transient Node<K,V>[] table; final Node<K,V>[] resize() { // 计算新hash表容量大小,begin 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; // 计算新hash表容量大小,end @SuppressWarnings({"rawtypes","unchecked”}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // #1 table = newTab; // #2 // rehash begin 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; } } } } } // rehash end return newTab; }
在代码#1 位置,用新计算的容量 new 了一个新的 hash 表,#2 将新创建的空 hash 表赋值给实例变量 table。
注意此时实例变量 table 是空的。
那么,如果此时另一个线程执行 get 时,就会 get 出 null。
3 JDK7 中 HashMap 并发 put 会造成循环链表,导致 get 时出现死循环
此问题在 JDK8 中已经解决。
3.1 JDK7 中循环链表的形成
发生在多线程并发 resize 的情况下。
相关源码如下:
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. */ // 关键在于这个transfer方法,这个方法的作用是将旧hash表中的元素rehash到新的hash表中 void transfer(Entry[] newTable, boolean rehash) { int newCapacity = newTable.length; for (Entry<K,V> e : table) { // table变量即为旧hash表 while(null != e) { // #1 Entry<K,V> next = e.next; if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } // 用元素的hash值计算出这个元素在新hash表中的位置 int i = indexFor(e.hash, newCapacity); // #2 e.next = newTable[I]; // #3 newTable[i] = e; // #4 e = next; } } }
假设线程 1(t1)和线程 2(t2)同时 resize,两个线程 resize 前,两个线程及 hashmap 的状态如下
堆内存中的 HashMap 对象中的 table 字段指向旧的 hash 表,其中 index 为 7 的位置有两个元素,我们以这两个元素的 rehash 为例,看看循环链表是如何形成的。
线程 1 和线程 2 分别 new 了一个 hash 表,用 newTable 字段表示。
PS:如果将每一步的执行都以图的形式呈现出来,篇幅过大,这里提供一下每次循环结束时的状态,可以根据代码和每一步的解释一步一步推算。
Step1: t2 执行完#1 代码后,CPU 且走执行 t1,并且 t1 执行完成
这里可以根据上图推算一下,此时状态如下
用 t2.e 表示线程 2 中的局部变量 e,t2.next 同理。
Step2: t2 继续向下执行完本次循环
Step3: t2 继续执行下一次循环
Step4: t2 继续下一次循环,循环链表出现
3.2 死循环的出现
HashMap.get 方法源码如下:
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); // 遍历链表 for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; // 假设这里条件一直不成立 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }
由上图可知,for 循环中的 e = e.next 永远不会为空,那么,如果 get 一个在这个链表中不存在的 key 时,就会出现死循环了。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于