Can any concurrent expert explain in ConcurrentHashMap, which concurrent features improved comparing with which in previous JDKs
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:
- Lazy initialization: in JDK8, the memory used for each segment is allocated only when some entity is added to the map. In JDK7,this is done when the map is created.
- Some new function is added in JDK8 like forEach, reduce, search etc.
- Inner structure change : the TreeBin (red-black tree) is used in jdk8 to improve the search efficiency.
来源:https://stackoverflow.com/questions/36571873/why-segment-dropped-in-java-8-concurrent-hashmap