[concurrency-interest] Is java.lang.String threadsafe?
Howard Lewis Ship
hlship at gmail.com
Sat Feb 10 18:23:03 EST 2007
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.
--
Howard M. Lewis Ship
TWD Consulting, Inc.
Independent J2EE / Open-Source Java Consultant
Creator and PMC Chair, Apache Tapestry
Creator, Apache HiveMind
Professional Tapestry training, mentoring, support
and project work. http://howardlewisship.com
More information about the Concurrency-interest
mailing list