Re: JavaMemoryModel: Object.hashCode() and System.identityHashCode()

From: Jeremy Manson (
Date: Sun Apr 18 2004 - 11:30:34 EDT

> Now, the usage is:
> Initially, obj = null.
> Thread 1:
> obj = new X(3);
> Thread 2:
> X obj2 = obj;
> if (obj2 != null) {
> r1 = obj2.hashCode();
> r2 = obj2.hashCode();
> }
> Question: can r1 != r2 ?
> YES!
> However, I suggested that when removing the override
> of hashCode() in X, will result the same hashCode()
> value, even in this case.

What you are saying is that this class definition does not fulfill the
contract of hashCode(). This is true (although, typically, when stating
such a thing, we do make a distinction between whether it works in a
single-threaded way or not).

There are plenty of contracts in the APIs, but we don't enforce them in the
JMM spec. You could, for example, construct a similar example where we call
clone() twice and get two different results.

Now, you can argue that there should be a @threadsafe javadoc tag, but that
is a different conversation.

Furthermore, it sounds like what you want is initialization safety for
hashCode() for fields which are immutable (after all, if anyone changes the
value of x, it is perfectly acceptable that this not work). But if you
really want this, you could change x to final in your example, and it would
work fine.

None of this, of course, has anything to do with Object.hashCode() or
System.identityHashCode(), which should probably be thread-safe anyway (if
they aren't, it is probably a bug).

JavaMemoryModel mailing list -

This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:05 EDT