ConcurrentHashMap, which concurrent features improved in JDK8
任何并发专家都可以在ConcurrentHashMap中进行解释,与以前的JDK相比,这些并发功能得到了改进
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.
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.
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.
I think there are several changes compared with JDK7: