Search code examples
javajvmhashcode

System.identityHashCode() can the same hashCode be returned after an Object is GC'ed


Assume System.identityHashCode(object1)==123 and object1 is garbage collected. Is it possible that a new created object2 can have the same identity hash code as object1 had before it was GC'ed ?


Solution

  • Is it possible that a new created object2 can have the same identity hash code as object1 got before it was GC'ed ?

    Yes it is.

    The identity hashcode might be derived from the address of the object when the method is first called for the object. (Or it might be generated some other way. The spec allows a lot of different mechanisms to be used.)

    So, if the GC collects object1, and a new object object2 is allocated at the same address as the original one, and the new one may have the same hashcode as the original.

    Furthermore, if the GC moves object1 after the hashcode has been generated, the new object (object2) at object1's original. Then, you could then end up with two existing objects having the same hashcode.

    But neither of these things should be a problem. Hashcodes are not not designed to be identifiers for objects. (So don't try and use them as such.)


    My understanding of identity is that objects are unique inside a JVM at a given point in time.

    The identity is unique. The identity hashcodes are not. As the Object javadoc says:

    "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects."

    That is nowhere near a guarantee of uniqueness.

    And then:

    "(This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)"

    What it is referring to is the address of the object when hashCode() is first called. The contract for the hashCode() method states that the hashcode value cannot change. The identity hashcode is ... in effect ... remembered as part of the object so that the object can be moved by the GC.

    And note that the latest javadocs have dropped all mention of how an identity hashcode is or might be generated. This change happened in Java 12.