Java string hashcode caching mechanism

Looking at the Java string class, we can see that the hash code is cached after the 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;
}

Hash is an instance variable I have a question, why do we need this h extra variable?

Solution

Just because the hash value in the loop changes, the solution without intermediate temporary variables is not thread safe Consider calling this method in multiple threads.

Said that thread 1 started hash calculation, it is no longer 0 Later, thread - 2 calls the same method hashcode () on the same object and sees that the hash is not 0, but thread 1 has not completed its calculation Therefore, the value will be used in the hash (not fully calculated) of thread 2 error

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>