原文地址:http://www.journaldev.com/122/java-concurrenthashmap-example-iterator#comment-27448

Today we will look into Java ConcurrentHashMap Example. If you are a Java Developer, I am sure that you must be aware of ConcurrentModificationException that comes when you want to modify the Collection object while using iterator to go through with all its element. Actually Java Collection Framework iterator is great example of iterator design pattern implementation.

Java ConcurrentHashMap

Java 1.5 has introduced java.util.concurrent package with Collection classes implementations that allow you to modify your collection objects at runtime.

ConcurrentHashMap Example

ConcurrentHashMap is the class that is similar to HashMap but works fine when you try to modify your map at runtime.

Lets run a sample program to explore this:

ConcurrentHashMapExample.java

package com.journaldev.util;import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;public class ConcurrentHashMapExample {public static void main(String[] args) {//ConcurrentHashMapMap<String,String> myMap = new ConcurrentHashMap<String,String>();myMap.put("1", "1");myMap.put("2", "1");myMap.put("3", "1");myMap.put("4", "1");myMap.put("5", "1");myMap.put("6", "1");System.out.println("ConcurrentHashMap before iterator: "+myMap);Iterator<String> it = myMap.keySet().iterator();while(it.hasNext()){String key = it.next();if(key.equals("3")) myMap.put(key+"new", "new3");}System.out.println("ConcurrentHashMap after iterator: "+myMap);//HashMapmyMap = new HashMap<String,String>();myMap.put("1", "1");myMap.put("2", "1");myMap.put("3", "1");myMap.put("4", "1");myMap.put("5", "1");myMap.put("6", "1");System.out.println("HashMap before iterator: "+myMap);Iterator<String> it1 = myMap.keySet().iterator();while(it1.hasNext()){String key = it1.next();if(key.equals("3")) myMap.put(key+"new", "new3");}System.out.println("HashMap after iterator: "+myMap);}}

When we try to run the above class, output is

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1} ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1} HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1} Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) at java.util.HashMap$KeyIterator.next(HashMap.java:828) at com.test.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:44)

Looking at the output, its clear that ConcurrentHashMap takes care of any new entry in the map whereas HashMap throws ConcurrentModificationException.

Lets look at the exception stack trace closely. The statement that has thrown Exception is:

String key = it1.next();

It means that the new entry got inserted in the HashMap but Iterator is failing. Actually Iterator on Collection objects are fail-fast i.e any modification in the structure or the number of entry in the collection object will trigger this exception thrown by iterator.

So How does iterator knows that there has been some modification in the HashMap. We have taken the set of keys from HashMap once and then iterating over it.

HashMap contains a variable to count the number of modifications and iterator use it when you call its next() function to get the next entry.

HashMap.java

/*** The number of times this HashMap has been structurally modified* Structural modifications are those that change the number of mappings in* the HashMap or otherwise modify its internal structure (e.g.,* rehash).  This field is used to make iterators on Collection-views of* the HashMap fail-fast.  (See ConcurrentModificationException).*/transient volatile int modCount;

Now to prove above point, lets change the code a little bit to come out of the iterator loop when we insert the new entry. All we need to do is add a break statement after the put call.

if(key.equals("3")){ myMap.put(key+"new", "new3"); break; }

Now execute the modified code and the output will be:

ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1} ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1} HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1} HashMap after iterator: {3=1, 2=1, 1=1, 3new=new3, 6=1, 5=1, 4=1}

Finally, what if we won’t add a new entry but update the existing key-value pair. Will it throw exception?

Change the code in the original program and check yourself.

//myMap.put(key+"new", "new3");
myMap.put(key, "new3");

If you get confused (or shocked) with the output, comment below and I will be happy to explain it further.

Did you noticed those angle brackets while creating our collection object and Iterator, it’s called generics in java and it’s very powerful when it comes to type-checking at compile time to remove ClassCastException at runtime, learn more about generics in Java Generics Example.

转载于:https://www.cnblogs.com/davidwang456/p/6016897.html

Java ConcurrentHashMap Example and Iterator--转相关推荐

  1. java基础-迭代器(Iterator)与增强for循环

    java基础-迭代器(Iterator)与增强for循环 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Iterator迭代器概述 Java中提供了很多个集合,它们在存储元素时 ...

  2. Java中 Iterable 和 Iterator 的区别

    1.Iterable接口 Iterable接口 (java.lang.Iterable) 是Java集合的顶级接口之一.我们首先看下这这个接口在JDK中的定义: package java.lang; ...

  3. java queue iterator_Java DelayQueue iterator()用法及代码示例

    DelayQueue的iterator()方法用于在DelayQueue中的所有元素上返回迭代器.这些元素可以过期或未过期. 用法: public Iterator iterator () 参数:此方 ...

  4. Java ConcurrentHashMap 最佳实践

    2019独角兽企业重金招聘Python工程师标准>>> Java ConcurrentHashMap 最佳实践 博客分类: java 相对于HashMap,ConcurrentHas ...

  5. java enumerator_Enumerator迭代器和Iterator迭代器区别

    Enumerator迭代器和Iterator迭代器区别 Iterator也是一个接口,它的源码如下:package java.util; public interface Iterator { boo ...

  6. HashMap vs ConcurrentHashMap — 示例及Iterator探秘

    2019独角兽企业重金招聘Python工程师标准>>> 如果你是一名Java开发人员,我能够确定你肯定知道ConcurrentModificationException,它是在使用迭 ...

  7. java concurrenthashmap与阻塞队列

    https://blog.csdn.net/wozniakzhang/article/details/108106205 Java~并发容器ConcurrentHashMap.ConcurrentLi ...

  8. Java核心API -- 7(Iterator迭代器、Comparable、Comparator比较器)

    1. Iterator迭代器 所有Collection的实现类都实现了iterator方法,该方法返回一个Iterator接口类型的对象,用于实现对集合元素迭代的便利.在java.util包下. 1) ...

  9. java it_Java中的Iterator的用法

    Iterator(迭代器) 迭代器是一种设计模式,它是一个对象,可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构.迭代器通常器被称为"轻量级"对象,因为创建它的代价 ...

最新文章

  1. Linux下DIY DLAN投屏方案
  2. jquery对象PHP转换,jquery对象和DOM对象如何相互转换?
  3. 中国AI服务器,刷新全球18项性能基准测试纪录
  4. 文本比较算法Ⅶ——线性空间求最长公共子序列的Nakatsu算法
  5. JZOJ 1980. 【2011集训队出题】Construct
  6. 2021.08.25学习内容torch.clamp(input, min, max, out=None) → Tensor,torch.mm(matrix multiply)
  7. width 、 height 与 box-sizing : border-box ,content-box 的关系
  8. winform学习之-----页面设计-20160523
  9. Sweet Home 3D 是Web三维效果图
  10. python 3.6.3自带的编程调试环境包括了_序章:资料预处理(python3.6 可用fortran unformatted sequencial data读取模块)...
  11. linux 挂载raid_linux下做raid
  12. android 实现应用程序后台运行的说明
  13. Polar Si9000如何选择模型计算射频线宽?
  14. excel转word后表格超出页面_excel表格粘贴到word太宽显示不全怎么办?
  15. linux日志删除了还能恢复吗,Linux系统中恢复被删除日志的方法
  16. 坐火车硬座20小时是怎样的体验?
  17. EduCoder-Web程序设计基础-html5—结构元素-第3关:figure元素和figcaption元素的应用
  18. ping局域网里面全部的ip
  19. Verilog进阶思想和编程练习题库
  20. 再寄小读者之一:关于读书

热门文章

  1. php300类库,扩展类库 · PHP300FrameWork · 看云
  2. bootstrap 点击加号 表格_bootstrap中的输入组按钮,点击加号加1,减1子
  3. 将服务端移植到Linux和MAC OS
  4. Linux查看ssd块大小性能,如何衡量Linux中对SSD执行的总写入量?
  5. 图像识别python cnn_MINIST深度学习识别:python全连接神经网络和pytorch LeNet CNN网络训练实现及比较(一)...
  6. 解决bug_赛博朋克2077BUG卡关怎么办?卡关BUG解决办法
  7. Linux源码手机,Linux操作系统源代码详细分析
  8. java for循环优化_Java for循环优化
  9. 重置npm设置_密码重置用户流程4部曲
  10. java 之持久化和序列化(反序列化)