On 11/12/2009, Tim Ellison <[email protected]> wrote: > On 11/Dec/2009 04:09, Vijay Menon wrote: > > Perhaps I'm missing some context, but I don't see any problem. I don't > > believe that this: > > > > if (hashCode == 0) { > > // calculate hash > > hashCode = hash; > > } > > return hashCode; > > > > can ever return 0 (assuming hash is non-zero), regardless of memory fences. > > The JMM won't allow visible reordering in a single threaded program.
However hashCode is shared between threads, so without knowing what other threads do to hashCode (which is not shown above), it's possible the hashCode returned by the code might be different from the hash calculated in this thread. That does not involve re-ordering. For example, if the calculation stored intermediate results in hashCode, the return value could be different from the calculated value. As far as I can tell, this isn't the case here. > > I agree. In the multi-threaded case there can be a data race on the > hashCode, with the effect that the same hashCode value is unnecessarily, > but harmlessly, recalculated. However, it would be safer if the code fetched the hashCode and returned its local copy - and it might be slightly quicker, as there would be fewer accesses to the instance variable. > Regards, > > Tim >
