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

Dawid Kurzyniec dawidk at mathcs.emory.edu
Sat Feb 10 18:37:28 EST 2007


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)
>
>   

Correct. String class purposely allows race conditions, for sake of 
improved performance (through avoiding synchronization), which is OK 
here since races are benign due to (a) and (b) above. The only 
"negative" side effect is that several threads may re-do the work by 
independently computing the hash code, but it actually costs much less 
than blocking and waiting would in this case.

Regards,
Dawid




More information about the Concurrency-interest mailing list