Java ConcurrentHashMap 与同步 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1291836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ConcurrentHashMap vs Synchronized HashMap
提问by hello_world_infinity
What is the difference between using the wrapper class, SynchronizedMap
, on a HashMap
and ConcurrentHashMap
?
SynchronizedMap
在 aHashMap
和上使用包装类 , 有什么区别ConcurrentHashMap
?
Is it just being able to modify the HashMap
while iterating it (ConcurrentHashMap
)?
它只是能够HashMap
在迭代它时修改它 ( ConcurrentHashMap
) 吗?
采纳答案by Joey.zhgw
Synchronized HashMap
:
同步HashMap
:
Each method is synchronized using an object level lock. So the get and put methods on synchMap acquire a lock.
Locking the entire collection is a performance overhead. While one thread holds on to the lock, no other thread can use the collection.
每个方法都使用对象级锁进行同步。所以synchMap 上的get 和put 方法需要一个锁。
锁定整个集合是一种性能开销。当一个线程持有锁时,没有其他线程可以使用该集合。
ConcurrentHashMap
was introduced in JDK 5.
ConcurrentHashMap
是在 JDK 5 中引入的。
There is no locking at the object level,The locking is at a much finer granularity. For a
ConcurrentHashMap
, the locks may be at a hashmap bucket level.The effect of lower level locking is that you can have concurrent readers and writers which is not possible for synchronized collections. This leads to much more scalability.
ConcurrentHashMap
does not throw aConcurrentModificationException
if one thread tries to modify it while another is iterating over it.
没有对象级别的锁定,锁定的粒度要细得多。对于 a
ConcurrentHashMap
,锁定可能处于哈希图存储桶级别。较低级别锁定的效果是您可以拥有并发的读取器和写入器,这对于同步集合是不可能的。这导致更多的可扩展性。
ConcurrentHashMap
ConcurrentModificationException
如果一个线程试图修改它而另一个线程正在迭代它,则不会抛出 a 。
This article Java 7: HashMap vs ConcurrentHashMapis a very good read. Highly recommended.
这篇文章Java 7: HashMap vs ConcurrentHashMap是一本很好的读物。强烈推荐。
回答by trshiv
The short answer:
简短的回答:
Both maps are thread-safe implementations of the Map
interface. ConcurrentHashMap
is implemented for higher throughput in cases where high concurrency is expected.
这两个映射都是Map
接口的线程安全实现。ConcurrentHashMap
在需要高并发的情况下实现更高的吞吐量。
Brian Goetz's articleon the idea behind ConcurrentHashMap
is a very good read. Highly recommended.
Brian Goetz关于背后想法的文章ConcurrentHashMap
非常值得一读。强烈推荐。
回答by fastcodejava
ConcurrentHashMap
is thread safe without synchronizing the whole map. Reads can happen very fast while write is done with a lock.
ConcurrentHashMap
是线程安全的,无需同步整个地图。当使用锁完成写入时,读取可以非常快地发生。
回答by rai.skumar
ConcurrentHashMap
uses finer-grained locking mechanism known as lock stripping
to allow greater degree of shared access. Due to this it provides better concurrencyand scalability.
ConcurrentHashMap
使用更细粒度的锁定机制,lock stripping
以允许更大程度的共享访问。因此,它提供了更好的并发性和可伸缩性。
Also iterators returned for ConcurrentHashMap
are weakly consistentinstead of fail fast techniqueused by Synchronized HashMap.
此外,返回的迭代器ConcurrentHashMap
是弱一致的,而不是同步 HashMap 使用的快速失败技术。
回答by Renukeswar
Methods on SynchronizedMap
hold the lock on the object, whereas in ConcurrentHashMap
there's a concept of "lock striping" where locks are held on buckets of the contents instead. Thus improved scalability and performance.
SynchronizedMap
保持对象锁定的方法,而在ConcurrentHashMap
“锁定条带化”的概念中,锁定被锁定在内容的桶上。从而提高了可扩展性和性能。
回答by NarayanaReddy
ConcurrentHashMap :
并发哈希映射:
1)Both maps are thread-safe implementations of the Map interface.
1)两个map都是Map接口的线程安全实现。
2)ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.
2) ConcurrentHashMap 是为了在需要高并发的情况下实现更高的吞吐量。
3) There is no locking in object level.
3) 对象级别没有锁定。
Synchronized Hash Map:
同步哈希映射:
1) Each method is synchronized using an object level lock.
1) 每个方法都使用对象级锁进行同步。
回答by Ashraf.Shk786
Both are synchronized version of HashMap, with difference in their core functionality and their internal structure.
两者都是HashMap的同步版本,核心功能和内部结构不同。
ConcurrentHashMapconsist of internal segments which can be viewed as independent HashMaps Conceptually. All such segments can be locked by separate threads in high concurrent executions. So, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other. This is implemented for higher throughput.
ConcurrentHashMap由内部段组成,从概念上可以将其视为独立的 HashMap。所有这些段都可以在高并发执行中由单独的线程锁定。因此,多个线程可以从 ConcurrentHashMap 获取/放置键值对,而不会相互阻塞/等待。这是为了更高的吞吐量而实施的。
whereas
然而
Collections.synchronizedMap(), we get a synchronized version of HashMap and it is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.
Collections.synchronizedMap(),我们得到 HashMap 的同步版本,它以阻塞方式访问。这意味着如果多个线程尝试同时访问 synchronizedMap,它们将被允许以同步方式一次获取/放置一个键值对。
回答by Sumanth Varada
We can achieve thread safety by using both ConcurrentHashMap and synchronisedHashmap. But there is a lot of difference if you look at their architecture.
我们可以同时使用 ConcurrentHashMap 和 SynchronisedHashmap 来实现线程安全。但是如果你看看他们的架构,就会有很多不同。
- synchronisedHashmap
- 同步哈希图
It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you are comparing with ConcurrentHashMap.
它将在对象级别保持锁定。所以如果你想执行像 put/get 这样的任何操作,那么你必须先获取锁。同时,不允许其他线程执行任何操作。因此,一次只有一个线程可以对此进行操作。所以这里的等待时间会增加。和 ConcurrentHashMap 相比,可以说性能比较低。
- ConcurrentHashMap
- 并发哈希映射
It will maintain the lock at the segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.
If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.
So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap.
它将在段级别保持锁定。它有 16 个段,并且默认保持并发级别为 16。所以一次可以有 16 个线程可以操作 ConcurrentHashMap。而且,读操作不需要锁。因此,任意数量的线程都可以对其执行 get 操作。
如果thread1想在segment 2执行put操作,thread2想在segment 4执行put操作,这里是允许的。意味着,16 个线程可以同时对 ConcurrentHashMap 执行更新(放置/删除)操作。
这样在这里等待的时间就会少一些。因此性能相对优于同步哈希图。
回答by Vino
ConcurrentHashMapallows concurrent access to data. Whole map is divided into segments.
ConcurrentHashMap允许并发访问数据。整个地图被分成几段。
Read operation ie. get(Object key)
is not synchronized even at segment level.
读取操作即。get(Object key)
即使在段级别也不同步。
But write operations ie. remove(Object key), get(Object key)
acquire lock at segment level. Only part of whole map is locked, other threads still can read values from various segments except locked one.
但是写操作即。remove(Object key), get(Object key)
在段级别获取锁。只有整个地图的一部分被锁定,其他线程仍然可以从除了锁定的一个段之外的各个段读取值。
SynchronizedMapon the other hand, acquire lock at object level. All threads should wait for current thread irrespective of operation(Read/Write).
另一方面,SynchronizedMap在对象级别获取锁。无论操作(读/写)如何,所有线程都应等待当前线程。
回答by Pramod
As per java doc's
根据java doc的
Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent".
A concurrent collection is thread-safe, but not governed by a single exclusion lock.
In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability.
In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.
Hashtable 和 Collections.synchronizedMap(new HashMap()) 是同步的。但是 ConcurrentHashMap 是“并发的”。
并发集合是线程安全的,但不受单个排除锁的控制。
在 ConcurrentHashMap 的特殊情况下,它安全地允许任意数量的并发读取以及可调整数量的并发写入。当您需要通过单个锁阻止对集合的所有访问时,“同步”类可能很有用,但代价是可扩展性较差。
在期望多个线程访问公共集合的其他情况下,“并发”版本通常更可取。当集合未共享或仅在持有其他锁时才可访问时,最好使用非同步集合。