`
daniel.wuz
  • 浏览: 99905 次
  • 性别: Icon_minigender_1
  • 来自: 纽约
最近访客 更多访客>>
社区版块
存档分类

HashMap Collections.synchronized ConcurrentHashMap

阅读更多

在javadoc中找到这样一段话:

代码
  1. <p>The iterators returned by all of this class's "collection view methods"   
  2. * are <i>fail-fast</i>: if the map is structurally modified at any time after   
  3. * the iterator is created, in any way except through the iterator's own   
  4. <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a   
  5. <tt>ConcurrentModificationException</tt>.  Thus, in the face of concurrent   
  6. * modification, the iterator fails quickly and cleanly, rather than risking   
  7. * arbitrary, non-deterministic behavior at an undetermined time in the   
  8. * future.  
<script>render_code();</script>
如果hashmap在迭代的同时,被其他线程修改,则会抛出一个ConcurrentModificationException异常,如以下这段程序:
代码
  1. package hashmap;   
  2.   
  3. import java.util.HashMap;   
  4. import java.util.Iterator;   
  5. import java.util.Map;   
  6. import java.util.Set;   
  7. import java.util.Map.Entry;   
  8.   
  9. public class HashMapTest {   
  10.     private static final Map<Integer, Integer> map = new HashMap<Integer, Integer>();   
  11.   
  12.     public static void main(String[] args) {   
  13.         try {   
  14.             for (int i = 0; i < 10; i++) {   
  15.                 map.put(i, i);   
  16.             }   
  17.             new Thread() {   
  18.                 @Override  
  19.                 public void run() {   
  20.                     Set<Entry<Integer, Integer>> set = map.entrySet();   
  21.                     synchronized (map) {   
  22.                         Iterator<Entry<Integer, Integer>> it = set.iterator();   
  23.                         while (it.hasNext()) {   
  24.                             Entry<Integer, Integer> en = it.next();   
  25.                             System.out.println(en.getKey());   
  26.                         }   
  27.                     }   
  28.                 }   
  29.             }.start();   
  30.             for (int i = 0; i < 10; i++) {   
  31.                 map.put(i, i);   
  32.             }   
  33.         } catch (Throwable e) {   
  34.             e.printStackTrace();   
  35.         }   
  36.   
  37.     }   
  38. }   
<script>render_code();</script>

 

为了解决这个问题,jdk5.0以前的版本提供了Collections.SynchronizedXX();方法,对已有容器进行同步实现,这样容器在迭代时其他线程就不能同时进行修改了,但是由于Collections.SynchronizedXX()生成的容器把所有方法都进行了同步,其他线程如果只是读取数据也必须等待迭代结束。于是JDK5.0中新加了ConcurrentHashMap类,这个类通过内部独立锁的机制对写操作和读操作分别进行了同步,当一个线程在进行迭代操作时,其他线程也可以同步的读写,Iterator返回的只是某一时点上的,不会抛ConcurrentModificationException异常,比起hashmap效率也不会有太大损失

 

 

参考资料:Java 理论与实践: 构建一个更好的 HashMap

               Java Map 集合类简介

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics