Detailed explanation of the expansion process of Java ConcurrentHashMap

During the expansion process of ConcurrentHashMap, the following steps will be performed:

  1. Judgment of expansion conditions:
    When the number of elements in ConcurrentHashMap reaches the threshold (threshold), the expansion operation will be triggered. The threshold is calculated based on the load factor and the current hash table capacity. The load factor is a proportional value that measures how full the hash table is. Typically, the default value for the load factor is 0.75.

  2. Create a new hash table:
    During the expansion process, ConcurrentHashMap will create a new, larger-capacity hash table. The capacity of the new hash table is usually twice the capacity of the current hash table. At the same time, a new mask is generated to determine the position of the element in the new hash table.

  3. Segmented data migration:
    The data in ConcurrentHashMap is scattered and stored in multiple segments. During scaling, each segment is processed individually. For each segment, the elements in it are migrated. The goal of migration is to move elements from the old hash table to their corresponding positions in the new hash table.

  4. Data migration:
    During data migration, elements in each segment are processed. First, a lock on the current segment is acquired to ensure that other threads cannot modify the segment during the migration. Then, it will traverse the linked list or tree structure in the current segment, recalculate the hash value of the elements in it, and migrate them to the corresponding positions in the new hash table. During the migration process, atomic operations are used to ensure the correctness of the data.

  5. Complete the migration:
    During the migration process, the old and new hash tables coexist, and the old hash tables can still be read concurrently. When the migration is complete, the lock of the current segment will be released, and the internal state of ConcurrentHashMap will be updated, including the reference and capacity of the current hash table. At this point, the new hash table will be the main operation target, and the old hash table will be gradually discarded.

During the entire expansion process, read operations are lock-free and can continue to be performed concurrently. Only write operations need to acquire segment-level locks to ensure data consistency during migration.

It should be noted that the expansion operation of ConcurrentHashMap is performed segment by segment, and the entire hash table will not be globally locked. This segmented migration strategy enables ConcurrentHashMap to maintain high concurrency performance during the expansion process.

Guess you like

Origin blog.csdn.net/a772304419/article/details/131012692