Re: what the benefit is by using annotation, like "@Immutable" ?
Tom Anderson wrote:
To make this method safe, you either have to synchronize the whole thing,
or do the update of calculated and code atomically at the end.
Andreas Leitgeb wrote:
I'd have expected that if "calculated" was assigned *after* "code", that
would suffice without further synchronisation or volatile-ity of the fields.
Am I still too naive?
Yes. Don't omit what tom said about /happens-before/:
In fact, it's worse than that. Thread A could finish the method and update both calculated and code, but because there is no happens-before relationship between thread A and thread B, it's possible that B could come along later, and see the updated calculated but *not* the updated code. So even without an unlucky timeslice end, there is no guarantee of safety here.
Thread B could obtain a value of '0' even chronologically after the entire
calculation, absent synchronization.
Tom Anderson wrote:
course, were you to do this, you might want to avoid String's ability to
generate a code which looks like a flag indicating the lack of a code (ie
0). But then, you might think the one in four billion chance of it
happening was insignificant.
Andreas Leitgeb wrote:
I guess, I'd have spent one "if (h==0) { h=42; }" just before "hash = h;"
After the calculation loop, that extra "if" really wouldn't have hurt.
How is 42 any better than 0? And what, may I ask, is wrong with 0?
Has anyone found e.g. an english [sic] dictionary-word with hashCode 0, yet?
Or perhaps the name of some commonly used class in Java standard library
or some other String likely occurring in innocent code?
""
--
Lew