HashMap多线程操作扩容导致死循环

【转载】正如上篇文中所说,HashMap不是线程安全的,在被多线程共享操作时,会有问题,具体什么问题呢,一直没有个清晰的理解,今天写了个测试程序调了一下,才明白其中道理。

主要是多线程同时put时,如果同时触发了rehash操作,会导致HashMap中的链表中出现循环节点,进而使得后面get的时候,会死循环。【关于什么是rehash,读者可以自行去google了】

本文主要参考了:http://coolshell.cn/articles/9606.html,测试数据也一样。

测试代码:

[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.util.HashMap;  
  2.   
  3. public class HashMapInfiniteLoop {  
  4.       
  5.     private static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(2,0.75f);  
  6.     public static void main(String[] args) {  
  7.         map.put(555);  
  8.           
  9.         new Thread("Thread1") {  
  10.             public void run() {  
  11.                 map.put(777);  
  12.                 System.out.println(map);  
  13.             };  
  14.         }.start();  
  15.         new Thread("Thread2") {  
  16.             public void run() {  
  17.                 map.put(333);  
  18.                 System.out.println(map);  
  19.             };  
  20.         }.start();  
  21.           
  22.     }  
  23.   
  24. }  
其中,map初始化为一个长度为2的数组,loadFactor=0.75,threshold=2*0.75=1,也就是说当put第二个key的时候,map就需要进行rehash:


下面开始调试运行测试程序

(1)首先使Thread1和Thread2都停在run()的第一行:


此时map的内容为:


(2)Thread1调试进入JDK源代码,停在HashMap.transfer()方法内第一行,切换到Thread2,也停在HashMap.transfer()方法内第一行


此时map的内容为:

(3)切换到Thread1,停在HashMap.transfer()方法内477行【src[j] = null;】;切换到Thread2,也停在477行


(4)切换回Thread1,继续执行,停在图中480行:【int i = indexFor(e.hash, newCapacity);】


此时map内容没变,只是添加了代码中的e、next指针:



(5)切换回Thread2,直接把Thread2执行完毕:


此时map的内容为:


(6)切换回Thread1,回到transfer()方法中:


此时从调试信息中还可以清晰地看出map的内容:{5=55, 7=77, 3=33}

此时map形如:


(7)继续Thread1中的do-while循环,第一次循环过后,依旧【停在480行】:


(8)第二次循环过后,依旧【停在480行】:


(8)第二次循环过后,e已经为null,跳出循环:


(9)离开transfer()方法,回到resize方法中,将newTable赋值给map.table,此时在查看map,默认的toString()方法已经在死循环了


至此,map中数组索引位置为3的链表上已经成功的出现了环,再对map做索引位置为3的get操作,就会死循环在这里,CPU成功到达100%。

比如,调用map.get(11)时,即会引起死循环。

 

而且,map中还丢失了元素,(5,55)已经不再map中了。

猜你喜欢

转载自wzw5433904.iteye.com/blog/2319974
今日推荐