2 ms·
Object::hashCode returns System.identityHashCode(Object) by default. Since GC can move objects around in memory, and the hash code of an object needs to be stab
by layer8 2y ago
Object::hashCode returns System.identityHashCode(Object) by default. Since GC can move objects around in memory, and the hash code of an object needs to be stable, this default hash code can’t be based on the memory address of the object, and thus needs to be stored per object.
Since System.identityHashCode() can be invoked (for example by IdentityHashMap) even for objects of classes that implement a custom hash code, it also can’t be optimized away even for such classes.
Conceivably it could be optimized away for an object unless or until System.identityHashCode() is invoked for it. It could thus be allocated on demand similarly to how the object locks are. Of course, this has all kinds of performance trade-offs.