ConcurrentHashMap,JDK8 中改进的并发特性 [英] ConcurrentHashMap, which concurrent features improved in JDK8
问题描述
有没有并发高手能解释一下ConcurrentHashMap中并发特性和以前的JDK相比有哪些改进
Can any concurrent expert explain in ConcurrentHashMap, which concurrent features improved comparing with which in previous JDKs
推荐答案
好吧,ConcurrentHashMap
已经完全重写.在 Java 8 之前,每个 ConcurrentHashMap
都有一个在构建时固定的并发级别".出于兼容性原因,还有一个 接受这样一个级别的构造函数 尽管没有以原始方式使用它.映射被分成与它的并发级别一样多的段,每个段都有自己的锁,所以理论上,如果它们都碰巧针对不同的目标,那么理论上最多可以有并发级别并发更新段,这取决于散列.
Well, the ConcurrentHashMap
has been entirely rewritten. Before Java 8, each ConcurrentHashMap
had a "concurrency level" which was fixed at construction time. For compatibility reasons, there is still a constructor accepting such a level though not using it in the original way. The map was split into as many segments, as its concurrency level, each of them having its own lock, so in theory, there could be up to concurrency level concurrent updates, if they all happened to target different segments, which depends on the hashing.
在 Java 8 中,每个哈希桶都可以单独更新,因此只要没有哈希冲突,就可以进行与其当前容量一样多的并发更新.这符合 compute
保证原子更新的方法,因此,至少锁定更新的哈希桶.在最好的情况下,他们确实只锁定了那个桶.
In Java 8, each hash bucket can get updated individually, so as long as there are no hash collisions, there can be as many concurrent updates as its current capacity. This is in line with the new features like the compute
methods which guaranty atomic updates, hence, locking of at least the hash bucket which gets updated. In the best case, they lock indeed only that single bucket.
此外,ConcurrentHashMap
受益于应用于所有类型的哈希映射的一般哈希改进.当某个桶发生哈希冲突时,实现将求助于该桶内的类似结构的排序映射,从而降低到 O(log(n))
复杂度而不是 O(n)
搜索桶时旧实现的复杂性.
Further, the ConcurrentHashMap
benefits from the general hash improvements applied to all kind of hash maps. When there are hash collisions for a certain bucket, the implementation will resort to a sorted map like structure within that bucket, thus degrading to a O(log(n))
complexity rather than the O(n)
complexity of the old implementation when searching the bucket.
这篇关于ConcurrentHashMap,JDK8 中改进的并发特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!