Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the jvm assign hashcode value in the object header

Tags:

java

jvm

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?

  • If Yes. Why it havent invoke hashcode method, and without this how to calculate hashcode of this object.
  • If No. Uhhh... It make no sense that update hashcode in object header every invoke invoke hashCode method.
like image 627
nail fei Avatar asked Dec 18 '22 09:12

nail fei


1 Answers

  • 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.
like image 89
apangin Avatar answered Jan 19 '23 00:01

apangin