[Java concurrent programming] 23. Principle analysis of ConcurrentHashMap (comparison of 1.7 and 1.8 versions)

jdk version 1.8

The implementation of ConcurrentHashMap in 1.8 has basically changed compared to the 1.7 version. First, the data structure of Segment segment lock is cancelled, and replaced by the structure of array + linked list (red-black tree). As for the granularity of the lock, it is adjusted to lock each array element (Node).

The steps of put are roughly as follows:

    1. Parameter verification.
    2. Initialized if table[] is not created. The initialization and expansion of the table adopts the CAS lock-free design, and the concurrent operation of the thread is controlled by the state sizeCtl: U.compareAndSwapInt(this, SIZECTL, sc, -1)
    3. When there is no node behind table[i], Node is created directly (no lock operation). Also implemented through CAS: return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
    4. If currently expanding, help expand and return the latest table[].
    5. Then append nodes to the linked list or red-black tree. This process achieves thread safety by locking the current node with synchronized (f)
    6. If it is a linked list, traverse the linked list and replace the old value if the same key is found, and add it to the end of the linked list if the same key is not found
    7. If it is a red-black tree,
    8. Finally, go back to determine whether the threshold is reached, such as reaching a red-black tree structure. Usage: treeifyBin(tab, i);

 The get() method has no locking operation. The steps are as follows:

    1. First locate i in table[].
    2. If table[i] exists, continue searching.
    3. First compare the head of the linked list and return if it is.
    4. Then if it is a red-black tree, look up the tree.
    5. If it is not a red-black tree, circular linked list search.

Refer to the online detailed information as follows:

JDK1.8 implementation of ConcurrentHashMap

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325200207&siteId=291194637