java concurrenthashmap和hashmap的区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java concurrenthashmap和hashmap的区别相关的知识,希望对你有一定的参考价值。

最大的区别就是ConcurrentHashMap是线程安全的,hashMap不是线程安全的。
为什么线程安全呢:
ConcurrentHashMap代码中可以看出,它引入了一个“分段锁”的概念,具体可以理解为把一个大的Map拆分成N个小的HashTable,根据key.hashCode()来决定把key放到哪个HashTable中。
在ConcurrentHashMap中,就是把Map分成了N个Segment,put和get的时候,都是现根据key.hashCode()算出放到哪个Segment中:
参考技术A 1、ConcurrentHashMap对整个桶数组进行了分段,而HashMap则没有
2、ConcurrentHashMap在每一个分段上都用锁进行保护,从而让锁的粒度更精细一些,并发性能更好,而HashMap没有锁机制,不是线程安全的
参考技术B 即使是线程安全的集合,使用iterator()进行迭代都是不安全的,必须手动地进行同步,下面是JavaDoc的说明:Itisimperativethattheusermanuallysynchronizeonthereturnedmapwheniteratingoveranyofitscollectionviews:Mapm=Collections.synchronizedMap(newHashMap());Sets=m.keySet();//Needn'tbeinsynchronizedblocksynchronized(m)//Synchronizingonm,nots!Iteratori=s.iterator();//Mustbeinsynchronizedblockwhile(i.hasNext())foo(i.next());如果不使用同步块进行迭代,当在迭代时,如果存在另外一个线程对集合进行删除或者添加元素,则会报ConcurrentModificationException

以上是关于java concurrenthashmap和hashmap的区别的主要内容,如果未能解决你的问题,请参考以下文章

ConcurrentHashMap原理分析

ConcurrentHashMap 的实现原理

HashMap ConcurrentHashMap解读

JAVA:并发

Java中的ConcurrentHashMap和Hashtable [重复]

java ConcurrentHashMap 初识