在javadoc中找到这样一段话:
代码
- * <p>The iterators returned by all of this class's "collection view methods"
- * are <i>fail-fast</i>: if the map is structurally modified at any time after
- * the iterator is created, in any way except through the iterator's own
- * <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
- * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
- * modification, the iterator fails quickly and cleanly, rather than risking
- * arbitrary, non-deterministic behavior at an undetermined time in the
- * future.
<script>render_code();</script>
如果hashmap在迭代的同时,被其他线程修改,则会抛出一个ConcurrentModificationException异常,如以下这段程序:
代码
- package hashmap;
-
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.Map.Entry;
-
- public class HashMapTest {
- private static final Map<Integer, Integer> map = new HashMap<Integer, Integer>();
-
- public static void main(String[] args) {
- try {
- for (int i = 0; i < 10; i++) {
- map.put(i, i);
- }
- new Thread() {
- @Override
- public void run() {
- Set<Entry<Integer, Integer>> set = map.entrySet();
- synchronized (map) {
- Iterator<Entry<Integer, Integer>> it = set.iterator();
- while (it.hasNext()) {
- Entry<Integer, Integer> en = it.next();
- System.out.println(en.getKey());
- }
- }
- }
- }.start();
- for (int i = 0; i < 10; i++) {
- map.put(i, i);
- }
- } catch (Throwable e) {
- e.printStackTrace();
- }
-
- }
- }
<script>render_code();</script>
为了解决这个问题,jdk5.0以前的版本提供了Collections.SynchronizedXX();方法,对已有容器进行同步实现,这样容器在迭代时其他线程就不能同时进行修改了,但是由于Collections.SynchronizedXX()生成的容器把所有方法都进行了同步,其他线程如果只是读取数据也必须等待迭代结束。于是JDK5.0中新加了ConcurrentHashMap类,这个类通过内部独立锁的机制对写操作和读操作分别进行了同步,当一个线程在进行迭代操作时,其他线程也可以同步的读写,Iterator返回的只是某一时点上的,不会抛ConcurrentModificationException异常,比起hashmap效率也不会有太大损失
参考资料:Java 理论与实践: 构建一个更好的 HashMap
Java Map 集合类简介
分享到:
相关推荐
HASHMAP缓存.txt HASHMAP缓存.txt
HashMap类.rar
HashMap,HashTable,ConcurrentHashMap 之关联 HashMap、HashTable、ConcurrentHashMap 是 Java 集合类中的重点,以下是对它们的详细解释: HashMap HashMap 是非线程安全的,它的键和值都允许有 null 值存在。...
HashMap存放.doc
java中HashMap详解.pdf
51. ArrayList LinkedList Set HashMap介绍.txt
模拟java中的HashMap类js类对象,可以与js的Array类对象配合使用
HashMap是一个散列桶(数组和链表),它存储的内容是键值对(key-value)映射HashMap采用了数组和链表的数据结构,能在查询和修改方便继承了数组的线性查找和链表的寻址修改HashMap是非synchronized,所以HashMap很快...
如果我么需要有一个线程安全的HashMap,可以使用Collections.synchronizedMap(Map m)方法获得线程安全的HashMap,也可以使用ConcurrentHashMap类创建线程安全的map。 存储的元素在jdk1.7当中是Entry作为存储的
多线程环境下,建议使用 ConcurrentHashMap,或者使用 Collections.synchronizedMap(hashMap) 将 HashMap 转成线程同步的。 只能使用关联的键来获取值。 HashMap 只能存储对象,所以基本数据类型应该使用其包装器...
自己写的例子,关于HashSet遍历和HashMap遍历的. 感谢大家参考
HashMap原理解析
HashMap& ConcurrentHashMap 深度解析
HashMap简介
HashMap
深入解读java面试必考基本功-HashMap合集 (blibli)
HashMap原理简介,Java初学者
2020-02-22突然间失业,找工作,目前在租的房子里面学习怎么样提高自己的奇数水平,要找工作了。好好学习,一些资料放在这儿。HashMap的手写版本,让你更能明白底层原理