请高手指教,学习JDK原码时发现的问题
binny 2003-10-30 05:12:16 java.util.Locale类中的writeObject方法
private void writeObject(ObjectOutputStream out) throws IOException {
// hashcode is semantically transient. We couldn't define it as transient
// because versions of this class that DIDN'T declare it as transient have
// already shipped. What we're doing here is making sure that the written-out
// version of hashcode is always -1, regardless of what's really stored there
// (we hold onto the original value just in case someone might want it again).
// Writing -1 ensures that version 1.1 Locales will always recalculate their
// hash codes after being streamed back in. This is necessary because
// String.hashCode() calculates its hash code differently in 1.2 than it did
// in 1.1.
int temp = hashcode;
hashcode = -1; //<--这里
out.defaultWriteObject();
hashcode = temp;
}
如果运行到hashcode = -1;而out.defaultWriteObject();没有运行到的时候。有别的进程调用hashcode();方法
public synchronized int hashCode() {
if (hashcode == -1) {
hashcode =
language.hashCode() ^
country.hashCode() ^
variant.hashCode();
}
return hashcode;
}
这样写文件中的hashcode 不就不是-1了吗。
是不是应该这样写呢
synchronized(hashcode) {
int temp = hashcode;
hashcode = -1;
out.defaultWriteObject();
hashcode = temp;
}
小弟一时想到的,不知道对不对,请高手指教