Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a Java String hash code lazy generated?

It appears in java.lang.String.java, that Java will only generate the hashcode, and then store it, after a call to hashcode(), but why not just make the hashcode in the constructor?

The relevant code:

if (h == 0 && count > 0) {
    int off = offset;
    char val[] = value;
    int len = count;

    for (int i = 0; i < len; i++) {
        h = 31*h + val[off++];
    }

    hash = h;
}

could for the most part be placed in the constructor.

like image 931
sneeze1 Avatar asked Feb 17 '12 00:02

sneeze1


2 Answers

Why spend time generating a hash code that most likely will not be used? Most strings are constructed, used and then garbage collected without the hashcode() ever being called.

like image 74
Skip Head Avatar answered Oct 09 '22 09:10

Skip Head


Joshua Bloch call this practice 'racy single-check'.

Jeremy Manson has excellent explanation of why it's done and why it'safe: on his blog

In essence, at construction time you save some time by skipping calculating hash code. In multithreaded environment you'll pay for this back because multiple thread potentially could do the same calculation.

like image 41
Petro Semeniuk Avatar answered Oct 09 '22 10:10

Petro Semeniuk