Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

String, hashCode and thread-safety

807589Sep 23 2008 — edited Sep 23 2008
Hi
I was just having a dig around the java.lang.String class and noticed the hash code is cached in a private int variable "hash" the first time hashCode() is called.
    public int hashCode() { 
int h = hash; 
if (h == 0) { 
    int off = offset; 
    char val[] = value; 
    int len = count; 

            for (int i = 0; i < len; i++) { 
                h = 31*h + val[off++]; 
            } 
            hash = h; 
        } 
        return h; 
    }
I appreciate the String object is inherently threadsafe due to the fact it is immutable, but how does the caching of the hash code stand when multiple threads concurrently access the hashCode() method on String for the first time? i.e. what will happen if a first thread is reassigning the instance variable "hash" to the calculated value (hash = h;) at the same time a second thread is assigning "hash" to the local int (int h = hash;). Is there potential that the second thread could view "hash" in an inconsistent state, or does the memory model guarantee that "hash" can only ever be zero or the correct hash value? Even if the second thread saw hash as zero whilst it was being calculated by the first thread the I guess calculating the hash code a second time around wouldn't really be a huge overhead? I guess this is a question around how the memory model manages visibility of local instance variables whilst the variable reference is being reassigned. Also does this vary for primitive and object types?

Thanks in advance
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 21 2008
Added on Sep 23 2008
4 comments
1,007 views