Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"hash" variable in String class

Tags:

java

jvm

what is the use of private "hash" variable in java.lang.String class. It is private and calculated/re-calculated every time hashcode method is called.

http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java

like image 611
Peeyush Avatar asked Jan 20 '26 03:01

Peeyush


1 Answers

It's used to cache the hashCode of the String. Because String is immutable, its hashCode will never change, so attempting to recalculate it after it's already been calculated is pointless.

In the code that you've posted, it's only recalculated when the value of hash is 0, which can either occur if the hashCode hasn't been calculated yet or if the hashCode of the String is actually 0, which is possible!

For example, the hashCode of "aardvark polycyclic bitmap" is 0.

This oversight seems to have been corrected in Java 13 with the introduction of a hashIsZero field:

public int hashCode() {
    // The hash or hashIsZero fields are subject to a benign data race,
    // making it crucial to ensure that any observable result of the
    // calculation in this method stays correct under any possible read of
    // these fields. Necessary restrictions to allow this to be correct
    // without explicit memory fences or similar concurrency primitives is
    // that we can ever only write to one of these two fields for a given
    // String instance, and that the computation is idempotent and derived
    // from immutable state
    int h = hash;
    if (h == 0 && !hashIsZero) {
        h = isLatin1() ? StringLatin1.hashCode(value)
                       : StringUTF16.hashCode(value);
        if (h == 0) {
            hashIsZero = true;
        } else {
            hash = h;
        }
    }
    return h;
}
like image 113
Jacob G. Avatar answered Jan 21 '26 18:01

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!