码迷,mamicode.com
首页 > 其他好文 > 详细

Collections.synchronizedMap()与ConcurrentHashMap的区别

时间:2017-02-17 23:52:43      阅读:400      评论:0      收藏:0      [点我收藏+]

标签:read   行数据   线程   ann   精确   ati   public   区别   runnable   

  前面文章提到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显然没法保证结果的有序。

Collections.synchronizedMap()与ConcurrentHashMap的区别

标签:read   行数据   线程   ann   精确   ati   public   区别   runnable   

原文地址:http://www.cnblogs.com/huajiezh/p/6411674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!