SoFunction
Updated on 2025-04-24

Java implements ThreadLocalMap expansion mechanism

ThreadLocalMapThe capacity expansion mechanism is used to adjust the array size when the number of stored entries exceeds the current array capacity to improve performance and reduce hash collisions. The scaling process involves creating a larger array, rehashing existing entries, and updating thresholds.

Expansion process

The capacity expansion process usually includes the following steps:

Determine whether capacity expansion is required

  • ThreadLocalMapMaintain a threshold (threshold), when the current number of entries is close to this threshold, the capacity expansion is triggered. Specifically, whensize >= thresholdWhen the capacity expansion is triggered.

Trigger capacity expansion

  • During the expansion process,ThreadLocalMapCreate a new, larger array (usually twice the size of the current array).

Rehash the entry

  • Rehash the entries from the old array into the new array. Since the new array is larger, the possibility of hash conflicts is reduced, which helps improve lookup efficiency.

Update threshold

  • After expansion, the threshold is updated to accommodate the new array size, usually 2/3 of the new array length.

Analysis of the code related to expansion

The following isThreadLocalMapKey code snippets for processing capacity expansion:

private void rehash() {
    expungeStaleEntries(); // Clear out obsolete entries
    if (size >= threshold - threshold / 4)
        resize(); // Expand capacity}

// Expand capacityprivate void resize() {
    Entry[] oldTab = table; // Old table    int oldLen = ; // Old length    int newLen = oldLen * 2; // New length    Entry[] newTab = new Entry[newLen]; // Create a new table    int count = 0;

    for (int j = 0; j < oldLen; ++j) {
        Entry e = oldTab[j]; // traverse old entries        if (e != null) {
            ThreadLocal<?> k = ();
            if (k == null) {
                 = null; // Clean up invalid values            } else {
                int h =  & (newLen - 1); // Calculate the position in the new table                while (newTab[h] != null)
                    h = nextIndex(h, newLen); // Handle conflicts                newTab[h] = e; // Insert to new table                count++;
            }
        }
    }

    setThreshold(newLen); // Update threshold    size = count; // Update the number of entries    table = newTab; // Update table references}

Key points analysis

expungeStaleEntries()

  • Called before expansionexpungeStaleEntries()Method, clear all outdated entries (that is, the key isnull) to ensure that invalid entries are not moved to the new table when scaling.

Create a new array

  • newTabIt is the new array after expansion, and its size is twice that of the old array.

Rehash

  • Iterates through each entry in the old array, calculates its position in the new array, and handles possible hash collisions.

Update threshold

  • The new threshold is 2/3 of the new array length. This threshold determines when the next expansion will be triggered.

Conflict handling

  • Linear detection method (nextIndex) Handle hash conflicts. While new arrays reduce conflicts, possible conflicts still need to be handled.

Summarize

ThreadLocalMapThe scaling mechanism improves performance by creating larger arrays and rehashing existing entries. The scaling process includes cleaning outdated entries, calculating the location of a new array, handling hash collisions, and updating thresholds. Doing so effectively reduces hash conflicts, improves lookup efficiency, and ensuresThreadLocalMapThe performance of   remains stable as the number of stored entries increases.

This is the end of this article about Java's ThreadLocalMap expansion mechanism. For more related Java ThreadLocalMap expansion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!