java String hashcode caching mechanism

user3673623 :

Looking at Java's String class we can see that hash code is cached after first evaluation.

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Where hash is an instance variable. I have a question, why do we need that h extra variable?

Andremoniy :

Simply because hash value changes in the loop and your solution without intermediate temporary variable is not thread-safe. Consider that this method is invoked in several threads.

Say thread-1 started hash computation and it is not 0 anymore. Some small moment later thread-2 invokes the same method hashCode() on the same object and sees that hash is not 0, but thread-1 hasn't yet finished its computation. As the result, in the thread-2 wrong hash (not fully computed) value will be used.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442483&siteId=1