If I call the Object.hashcode() method on some object it returns the internal address of the object (default implementation). Is this address a logical or physical address?
In garbage collection, due to memory compaction objects shifting takes place in the memory. If I call hashcode before and after the GC, will it return the same hashcode (it returns) and if yes then why (because of compaction address may change) ?
@erickson is more or less correct. The hashcode returned by
java.lang.Object.hashCode()does not change for the lifetime of the object.The way this is (typically) implemented is rather clever. When an object is relocated by the garbage collector, its original hashcode has to be stored somewhere in case it is used again. The obvious way to implement this would be to add a 32 bit field to the object header to hold the hashcode. But that would add a 1 word overhead to every object, and would waste space in the most common case … where an Object’s
hashCodemethod is not called.The solution is to add two flag bits to the object’s flag word, and use them (roughly) as follows. The first flag is set when the
hashCodemethod is called. A second flag tells thehashCodemethod whether to use the object’s current address as the hashcode, or to use a stored value. When the GC runs and relocates an object, it tests these flags. If the first flag is set and second one is unset, the GC allocates one extra word at the end of the object and stores the original object location in that word. Then it sets the two flags. From then on, thehashCodemethod gets the hashcode value from the word at the end of the object.In fact, an
identityHashCodeimplementation has to behave this way to satisfy the following part of the general hashCode contract:A hypothetical implementation of
identityHashCode()that simply returned the current machine address of an object would violate the highlighted part if/when the GC moved the object to a different address. The only way around this would be for the (hypothetical) JVM to guarantee that an object never moves oncehashCodehas been called on it. And that would lead to serious and intractable problems with heap fragmentation.