T
Thomas Hawtin
Roedy said:An hashcode is assigned in the constructor. Only one thread can
possibly see an object as it is being constructed.
Actually there were two thread-safety bugs in the initial example code,
but one wouldn't usually be considered as such.
The important problem is the access to the static field. Two objects
could be created at the same time. That could lead to the second
thread's constructor run loading a value between the first's load and store.
The second problem is that Java does not guarantee anything remotely
like Sequential Consistency. You may create an object and then store a
reference to it. But there is not a guarantee that another thread will
see it in the same order. Prior to 1.4 you could ensure correct
behaviour with client code that recklessly uses objects of your class
between threads without correct synchronisation. However you would
require a synchronized block in both the constructor (very rare) and the
hashCode method. From 1.5 you can just define the field final (and make
sure not to leak this from the constructor).
Sun's implementation of Object.hashCode appears to assign the identity
hashcode lazily. Presumably to keep the allocation code as short as
possible.
Tom Hawtin