Advantages of ConcurrentHashMap over HashMap

  1. ConcurrentHashMap uses each head node of the linked list as a lock object, and converts a large lock into multiple small locks, which greatly reduces the probability of lock conflicts. HashTable locks the
    insert image description here
    entire Hash table, so as long as a thread grabs the lock, other threads have to Blocking and waiting.
    insert image description here
    ConcurrentHashMap locks each linked list, so as long as the same linked list is not modified, it will not block, which greatly improves the efficiency

  2. ConcurrentHashMap adopts a more radical approach, only locks for writes, not for reads, and prevents dirty reads through volatile + atomic write operations.

  3. ConcurrentHashMap makes full use of CAS internally to further reduce the number of locking operations.

  4. ConcurrentHashMap adopts the method of "breaking the whole into zero" for the expansion mechanism.
    The expansion mechanism of HashMap and HashTable is: create a larger array space, and move each element of the linked list on the old array to the new array. This operation It will be triggered at a certain put, which will be very time-consuming when there is a lot of data.
    ConcurrentHashMap expansion adopts the method of moving a small number of elements each time. When creating a new array, the old array It will also be retained. Each put operation adds to the new array, and at the same time carries out a part of the transfer. Every time the get is checked, the two arrays will be queried, and the old array will be released after the data is transferred.

Guess you like

Origin blog.csdn.net/m0_71645055/article/details/131924602