[concurrency-interest] Is java.lang.String threadsafe?

Brian Goetz brian at quiotix.com
Sat Feb 10 20:01:40 EST 2007


This is a data race (writes and reads to a field not ordered by 
synchronization), but a benign one, because the hash field can take on 
only one nondefault value, and if multiple threads write to hash, they 
will always write the same value.  So all threads will either use the 
value computed by another thread, or will compute that same value for 
themselves.  See the footnote on p47 of JCiP.

Howard Lewis Ship wrote:
> I was just putting together a utility class (a non-case-sensitive
> String Map implementation) and I happened to look at some code in
> java.lang.String:
> 
>   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;
>     }
> 
> All the hallmarks of non-threadsafe code.  I think this is only
> threadsafe because:
> 
> a) In any race condition, it will always compute the same value
> (everything else is final)
> b) The field type is int, not long (atomic write for int, non-atomic for long)
> 
> I have a feeling I'm right here, if only because otherwise nothing in
> the JDK that uses a String is likely threadsafe.
> 


More information about the Concurrency-interest mailing list