nail fei
nail fei

Reputation: 2319

When does the jvm assign hashcode value in the object header

I have learned that the java object header contains the information such as hashcode、gc year、biased lock and so on. Then a puzzle come to me and in order express my question explicitly. I give an example.
Here is the code:

public class Demo{
    @Override
    public int hashCode(){
        System.out.println("the hashCode method was called");
        return super.hashCode();
    }

    public static void main(String[] args){
        Demo demo = new Demo();
        System.out.println("after generate an object");
        //
        Set<Demo> set = new HashSet<Demo>();
        set.add(demo);
    }
}

And the output:

after generate an object
the hashCode method was called

I guess when we new an object the jvm will set hashcode in object header. But if this in order to generate hashCode it should be invoke hashCode method of this object. However according to the output which seemed it havent invoke hashCode method when new an object. And add value into hashSet the hashCode method is invoked, this as was expected.

So my question is that: When does the jvm assign hashcode value in the object header? It happened in the phase when new an object?

Upvotes: 4

Views: 846

Answers (2)

apangin
apangin

Reputation: 98350

  • JVM does not need to call hashCode method to initialize object's identity hashCode. It works the other way round: Object.hashCode and System.identityHashCode call JVM to compute or to extract previously computed identity hashCode.
  • It is not specified how JVM generates and stores identity hashCode. Different JVM implementations may do it differently.
  • HotSpot JVM computes identity hashCode on the first call to Object.hashCode or System.identityHashCode and stores it in the object header. The subsequent calls simply extract the previously computed value from the header.

Upvotes: 6

dpr
dpr

Reputation: 10964

I think you are confusing hashcode and identity-hashcode.

An object's hashcode will not be stored in the object header but is computed by calling the hashcode method as needed. In your example hashcode is called because you are adding your object to a HashSet.

The identity hashcode is computed by the JVM at object creation and serves - amongst others - as fallback for an object's hashcode value. That is Object.hashcode() will return the identity hashcode of your object. This value will not change during the lifetime of your object.

See this question for further details.

Upvotes: 5

Related Questions