Analysis of the underlying structure of ConcurrentHashMap

ConcurrentHashMap of jdk1.7

  • The underlying data structure: segmented array + linked list . ConcurrentHashMap is composed of Segment data structure and HashEntry data structure. Segment implements ReentrantLock, so Segment is a reentrant lock and plays the role of lock. HashEntry is used to store key-value pair data. A ConcurrentHashMap contains an array of Segments. Each element in the Segment array contains a HashEntry array, and each element in the HashEntry array is an element of a linked list structure. Each element of the Segment array guards a single element in the HashEntry array. When modifying the data of the HashEntry array, you must first obtain the lock of the corresponding Segment array element.
    Insert picture description here

  • The way to achieve thread safety: first divide the data into a segment of storage, and then assign a lock to each segment of data. When a thread occupies the lock to access one of the segments of data, the data of other segments can also be accessed by other threads, improving Concurrent access rate.

ConcurrentHashMap of jdk1.8

  • The underlying data structure: ConcurrentHashMap cancels the segment lock, uses CAS (Compare-and-Swap, compare and replace) and synchronized to ensure concurrency safety. The data structure is similar to that of HashMap1.8, which is an array + linked list/red-black tree . (After jdk1.6, many optimizations have been made to synchronized locks, such as biased locks, lightweight locks, spin locks, lock elimination, lock coarsening, etc.)
  • Ways to achieve thread safety:
    ①In jdk1.7 , ConcurrentHashMap uses segmented locks to segment the entire bucket array ( Segment ), each lock only locks a part of the container, and multiple threads access different data in the container Segment data will not generate lock contention and increase the concurrent access rate.
    to jdk1.8 time , synchronized lock only the first node of the current list, or red-black tree, so long as the hash does not conflict, will not produce concurrent, but also enhance the efficiency of N times.

ConcurrentHashMap of jdk1.8 (TreeBin: red-black tree node; Node: linked list node)
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_47768542/article/details/109094878