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:

  • 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.
  • 链接地址: http://www.djcxy.com/p/91898.html

    上一篇: 尽量减少JDK8 ConcurrentHashMap检查的锁定范围

    下一篇: ConcurrentHashMap,在JDK8中改进了并发功能