如何使用线程安全的HashMap

HashMap为什么线程不安全

导致HashMap线程不安全的原因可能有两种:

1、当多个线程同时使用put方法添加元素的时候,正巧存在两个put的key发生了碰撞(根据hash值计算的bucket一样),那么根据HashMap的存储原理,这两个key会添加多数组的同一个位置,这样一定会导致其中一个线程put的数据被覆盖丢失

2、当多个线程同时检测到元素个数超过哈希表的size*loadFloat的时候,这样会发生多个线程同时对Node数组进行扩容的操作(java1.8中HashMap使用Node实体来存放内容),都在重新计算元素位置以及拷贝数据,但最后只能有一个线程能成功的将扩容后的数组赋值给table,也就是说其他线程的都会丢失,并且各自线程的数据也会丢失。关于hashMap线程不安全这一点,《java并发编程的艺术》一书中是这么描述的:“hashMap在并发执行put操作会引起死循环,导致CPU利用率接近100%。因为多线程会导致HashMap的Node链表形成环数据结构,一旦形成环数据结构,Node的next节点永远不为空,就会在获取Node时产生死循环”。由此可知,HashMap的死循环是发生在扩容时。关于hashMap的死循环可参看一下文章:

何如使用线程安全的HashMap
实现线程安全的方式有三种,分别是使用HashTable、Collections.SynchronizeMap、ConcurrentHashMap。

我们先分别来看看三种数据结构的部分源码:

hashtable

 

[java] view plain copy

  1. <code class="language-java">   public <span style="color:#ff0000;">synchronized </span>V get(Object key) {  
  2.         Entry<?,?> tab[] = table;  
  3.         int hash = key.hashCode();  
  4.         int index = (hash & 0x7FFFFFFF) % tab.length;  
  5.         for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {  
  6.             if ((e.hash == hash) && e.key.equals(key)) {  
  7.                 return (V)e.value;  
  8.             }  
  9.         }  
  10.         return null;  
  11.     }</code>  

public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; } publicsynchronizedV remove(Object key) { Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> e = (Entry<K,V>)tab[index]; for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { modCount++; if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } count--; V oldValue = e.value; e.value = null; return oldValue; } } return null; }

 
 

SynchronizeMap

 
  1. public V put(K key, V value) {

  2. synchronized (mutex) {return m.put(key, value);}

  3. }

  4. public V remove(Object key) {

  5. synchronized (mutex) {return m.remove(key);}

  6. }

  7. public void putAll(Map<? extends K, ? extends V> map) {

  8. synchronized (mutex) {m.putAll(map);}

  9. }

  10. public void clear() {

  11. synchronized (mutex) {m.clear();}

  12. }

通过这部分源码可知,HashTable、Collections.SynchronizeMap都是通过对读写进行加锁操作来保证线程的安全,一个线程进行读写数据,其余线程等等,可想而知,性能可想而知。

ConcurrentHashMap

在java8中,ConcurrentHashMap摒弃了Segment,启用了一种新的算法实现CAS。关于ConcurrentHashMap工作机制请参考深入浅出ConcurrentHashMap1.8

下面我们通过一些代码来验证他们之前的线程安全以及效率问题:

 

[java] view plain copy

  1. <code class="language-java">package com.iresearch.idata.common.util.demo;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5.   
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8. import java.util.concurrent.ConcurrentHashMap;  
  9. import java.util.concurrent.ConcurrentMap;  
  10. import java.util.concurrent.ExecutionException;  
  11.   
  12. /** 
  13.  * @author: htc 
  14.  * @date: Created in 18:18 2017/12/20. 
  15.  */  
  16. public class ConcurrentMapWithMap {  
  17.     private static Map<String, Long> mapWordCounts = new HashMap<>();  
  18.     private static ConcurrentMap<String, Long> concurrentMapWordCounts = new ConcurrentHashMap<>();  
  19.     public static Logger logger = LoggerFactory.getLogger(ConcurrentMapWithMap.class);  
  20.     public static int count = 0;  
  21.   
  22.     public static long mapIncrease(String word) {  
  23.         Long oldValue = mapWordCounts.get(word);  
  24.         Long newValue = (oldValue == null) ? 1L : oldValue + 1;  
  25.         mapWordCounts.put(word, newValue);  
  26.         return newValue;  
  27.     }  
  28.   
  29.   
  30.     public static long ConcurrentMapIncrease(String word) {  
  31.         Long oldValue, newValue;  
  32.         while (true) {  
  33.             oldValue = concurrentMapWordCounts.get(word);  
  34.             if (oldValue == null) {  
  35.                 // Add the word firstly, initial the value as 1  
  36.                 newValue = 1L;  
  37.                 if (concurrentMapWordCounts.putIfAbsent(word, newValue) == null) {  
  38.                     break;  
  39.                 }  
  40.             } else {  
  41.                 newValue = oldValue + 1;  
  42.                 if (concurrentMapWordCounts.replace(word, oldValue, newValue)) {  
  43.                     break;  
  44.                 }  
  45.             }  
  46.         }  
  47.         return newValue;  
  48.     }  
  49.   
  50.     public static void mapWordCount() throws InterruptedException, ExecutionException {  
  51.         new Thread(new Runnable() {  
  52.             @Override  
  53.             public void run() {  
  54.                 int count = 0;  
  55.                 while (count++ < 10000) {  
  56.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.mapIncrease("work"));  
  57.                 }  
  58.             }  
  59.         }).start();  
  60.         new Thread(new Runnable() {  
  61.             @Override  
  62.             public void run() {  
  63.                 int count = 0;  
  64.                 while (count++ < 10000) {  
  65.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.mapIncrease("work"));  
  66.                 }  
  67.             }  
  68.         }).start();  
  69.         new Thread(new Runnable() {  
  70.             @Override  
  71.             public void run() {  
  72.                 int count = 0;  
  73.                 while (count++ < 10000) {  
  74.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.mapIncrease("work"));  
  75.                 }  
  76.             }  
  77.         }).start();  
  78.         new Thread(new Runnable() {  
  79.             @Override  
  80.             public void run() {  
  81.                 int count = 0;  
  82.                 while (count++ < 10000) {  
  83.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.mapIncrease("work"));  
  84.                 }  
  85.             }  
  86.         }).start();  
  87.     }  
  88.   
  89.     public static void concurrentWordCount() throws InterruptedException, ExecutionException {  
  90.         new Thread(new Runnable() {  
  91.             @Override  
  92.             public void run() {  
  93.                 int count = 0;  
  94.                 while (count++ < 10000) {  
  95.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.ConcurrentMapIncrease("work"));  
  96.                 }  
  97.             }  
  98.         }).start();  
  99.         new Thread(new Runnable() {  
  100.             @Override  
  101.             public void run() {  
  102.                 int count = 0;  
  103.                 while (count++ < 10000) {  
  104.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.ConcurrentMapIncrease("work"));  
  105.                 }  
  106.             }  
  107.         }).start();  
  108.         new Thread(new Runnable() {  
  109.             @Override  
  110.             public void run() {  
  111.                 int count = 0;  
  112.                 while (count++ < 10000) {  
  113.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.ConcurrentMapIncrease("work"));  
  114.                 }  
  115.             }  
  116.         }).start();  
  117.         new Thread(new Runnable() {  
  118.             @Override  
  119.             public void run() {  
  120.                 int count = 0;  
  121.                 while (count++ < 10000) {  
  122.                     logger.info("mapIncrease num is " + ConcurrentMapWithMap.ConcurrentMapIncrease("work"));  
  123.                 }  
  124.             }  
  125.         }).start();  
  126.     }  
  127.   
  128.     public static void main(String[] args) throws InterruptedException, ExecutionException {  
  129.         ConcurrentMapWithMap.mapWordCount();  
  130.         Thread.sleep(10000);  
  131.         //多线程累加,每次都少于40000,故线程不安全  
  132.         logger.info("final count map" + ConcurrentMapWithMap.mapWordCounts.get("work"));  
  133.         ConcurrentMapWithMap.concurrentWordCount();  
  134.         Thread.sleep(10000);  
  135.         //多线程累加,每次都是40000  
  136.         logger.info("final count concurrentMap" + ConcurrentMapWithMap.concurrentMapWordCounts.get("work"));  
  137.     }  
  138. }  
  139. </code>  

猜你喜欢

转载自blog.csdn.net/qq_40285302/article/details/82498891