zoukankan      html  css  js  c++  java
  • Collections.synchronizedMap()与ConcurrentHashMap的区别

      前面文章提到Collections.synchronizedMap()与ConcurrentHashM两者都提供了线程同步的功能。那两者的区别在哪呢?我们们先来看到代码例子。
        下面代码实现一个线程对map进行写操作,另一个线程,读出并打印map数据。

    [java] view plain copy
     
    1. package test.map;  
    2.   
    3. import java.util.Collections;  
    4. import java.util.HashMap;  
    5. import java.util.Hashtable;  
    6. import java.util.Map;  
    7. import java.util.Random;  
    8. import java.util.concurrent.ConcurrentHashMap;  
    9.   
    10. public class MapTest2 {  
    11.   
    12.     private static Map<String, Object> map1 = new HashMap<String, Object>();  
    13.     private static Map<String, Object> map2 = new Hashtable<String, Object>();  
    14.     private static Map<String, Object> map3 = new ConcurrentHashMap<String, Object>();  
    15.     private static Map<String, Object> map4 = Collections.synchronizedMap(new HashMap<String, Object>());  
    16.   
    17.     private static Map<String, Object> map = map4;  
    18.   
    19.     public static void main(String[] args) {  
    20.         new Thread(new Runnable() {  
    21.   
    22.             @Override  
    23.             public void run() {  
    24.                 while (true) {  
    25.                     if (map.size() > 0) {  
    26.                         for (Map.Entry<String, Object> entry : map.entrySet()) {  
    27.                             System.out.println(String.format("%s: %s", entry.getKey(), entry.getValue()));  
    28.                         }  
    29.                         map.clear();  
    30.                     }  
    31.                     try {  
    32.                         Thread.sleep((new Random().nextInt(10) + 1) * 1);  
    33.                     } catch (InterruptedException e) {  
    34.                         e.printStackTrace();  
    35.                     }  
    36.                 }  
    37.             }  
    38.         }).start();  
    39.   
    40.         new Thread(new Runnable() {  
    41.   
    42.             @Override  
    43.             public void run() {  
    44.   
    45.                 for (int i = 1; i <= 100; i++) {  
    46.                     map.put("key" + i, "value" + i);  
    47.                     try {  
    48.                         Thread.sleep((new Random().nextInt(10) + 1) * 1);  
    49.                     } catch (InterruptedException e) {  
    50.                         e.printStackTrace();  
    51.                     }  
    52.                 }  
    53.             }  
    54.         }).start();  
    55.     }  
    56. }  

    执行代码,我们发现当类中对象map值取map1,map2,map4时,程序都抛出Java.util.ConcurrentModificationException异常。当map=map3时,代码能正常运行。

    Collections.synchronizedMap()与ConcurrentHashMap主要区别是:Collections.synchronizedMap()和Hashtable一样,实现上在调用map所有方法时,都对整个map进行同步,而ConcurrentHashMap的实现却更加精细,它对map中的所有桶加了锁。所以,只要要有一个线程访问map,其他线程就无法进入map,而如果一个线程在访问ConcurrentHashMap某个桶时,其他线程,仍然可以对map执行某些操作。这样,ConcurrentHashMap在性能以及安全性方面,明显比Collections.synchronizedMap()更加有优势。同时,同步操作精确控制到桶,所以,即使在遍历map时,其他线程试图对map进行数据修改,也不会抛出ConcurrentModificationException。
        但是,细心的朋友可能发现了,上面的例子,即使map=map3时,最后打印的结果可以并没有100行。由于,不论Collections.synchronizedMap()还是ConcurrentHashMap对map同步的原子操作都是作用的map的方法上,map在读取与清空之间,线程间是不同步的。上面代码的不足在于,我们对这些同步的map过于信任,而忽略了混合操作带来的影响。正确的方法是,把map的读取和清空看成一个原子操作,给整个代码块加锁。

        还有一个区别是:ConcurrentHashMap从类的命名就能看出,它必然是个HashMap。而Collections.synchronizedMap()可以接收任意Map实例,实现Map的同步。看这个例子:

    [java] view plain copy
     
    1. package test.map;  
    2.   
    3. import java.util.Collections;  
    4. import java.util.HashMap;  
    5. import java.util.Map;  
    6. import java.util.TreeMap;  
    7. import java.util.concurrent.ConcurrentHashMap;  
    8.   
    9. public class MapTest4 {  
    10.   
    11.     private static void writeMap(Map<String, Object> map) {  
    12.         for (int i = 0; i < 10; i++) {  
    13.             map.put("key" + i, "value" + i);  
    14.         }  
    15.     }  
    16.   
    17.     private static void printMap(Map<String, Object> map) {  
    18.         for (Map.Entry<String, Object> entry : map.entrySet()) {  
    19.             System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());  
    20.         }  
    21.     }  
    22.   
    23.     public static void main(String[] args) {  
    24.         Map<String, Object> map1 = new HashMap<String, Object>();  
    25.         writeMap(map1);  
    26.         printMap(map1);  
    27.   
    28.         System.out.println();  
    29.   
    30.         Map<String, Object> map2 = Collections.synchronizedMap(new TreeMap<String, Object>());  
    31.         writeMap(map2);  
    32.         printMap(map2);  
    33.   
    34.         System.out.println();  
    35.   
    36.         Map<String, Object> map3 = new ConcurrentHashMap<String, Object>();  
    37.         writeMap(map3);  
    38.         printMap(map3);  
    39.     }  
    40. }  

    map2由于是个TreeMap,最后打印的结果有按照Key值排序的,而map3显然没法保证结果的有序。

  • 相关阅读:
    2020-11-15(第十一周)助教周小结
    2020-11-08(第十周)助教周小结
    2020-11-01助教周小结(第九周)
    Template.
    OO第四单元总结
    OO第三单元总结
    OO第二单元总结
    OO第一单元总结
    AFO
    Codeforces Round #424 (Div. 2)
  • 原文地址:https://www.cnblogs.com/huajiezh/p/6411674.html
Copyright © 2011-2022 走看看