Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the JVM ensure that System.identityHashCode() will never change?

Typically the default implementation of Object.hashCode() is some function of the allocated address of the object in memory (though this is not mandated by the JLS). Given that the VM shunts objects about in memory, why does the value returned by System.identityHashCode() never change during the object's lifetime?

If it is a "one-shot" calculation (the object's hashCode is calculated once and stashed in the object header or something), then does that mean it is possible for two objects to have the same identityHashCode (if they happen to be first allocated at the same address in memory)?

like image 574
butterchicken Avatar asked Jun 30 '09 10:06

butterchicken


People also ask

What is System identityHashCode in Java?

The java. lang. System. identityHashCode() is the method which is used to return the same hash code for any given object that is returned by the default method hashCode(). Also, for every hash code with a null reference zero is returned.

What is the difference between hashCode and identityHashCode?

The hashcode() method is a non-final instance method, and should be overridden in any class where the equals(Object) is overridden. By contrast, identityHashCode(Object) is a static method and therefore cannot be overridden.


1 Answers

Modern JVMs save the value in the object header. I believe the value is typically calculated only on first use in order to keep time spent in object allocation to a minimum (sometimes down to as low as a dozen cycles). The common Sun JVM can be compiled so that the identity hash code is always 1 for all objects.

Multiple objects can have the same identity hash code. That is the nature of hash codes.

like image 71
Tom Hawtin - tackline Avatar answered Oct 18 '22 04:10

Tom Hawtin - tackline