3. Object instantiated memory layout and access location

3.1 Several methods of object instantiation

  • new
  • Class newInstance() : reflection that calls only the constructor of empty arguments. Permission must be public
  • Constructor newInstance(Xxxx) : a reflection method that calls empty arguments and parameter constructors without permission requirements
  • With clone() : No arbitrary constructor is called
  • Use deserialization
  • Third-party library Objenesis

3.2 Six steps to create an object

  1. Determines whether an object’s corresponding class is loaded, linked, and initialized
  2. Allocates memory for objects
    1. If memory is neat, Pointers collide
    2. The memory is not tidy
      1. The virtual machine needs to maintain a list
      2. Free list allocation
  3. Handle concurrency security issues
    1. CAS failed retry and region locking are used to ensure atomicity of update
    2. Each thread is pre-allocated a TLAB
  4. Initializes the allocated space – All properties are set to default values, ensuring that the object instance fields can be used directly when not assigned
  5. Sets the object header of the object
  6. Execute the init method for initialization

3.3 Memory Layout of objects

Object memory layout:

  • Object head
  • The instance data
  • Padding: Not required, just a placeholder

Object head

  • Runtime metadata: Mark Word
    • Hash value
    • GC generational age
    • Lock status flag
    • Thread holding lock
    • Biased thread ID
    • Bias timestamp
  • Type pointer: Points to the class metadata InstanceKlass and determines the type to which the object belongs
  • If you create an array, you also record the length of the array

The instance data

Instance data is the valid information that the object actually stores, and contains fields of various types defined in the program code (including fields inherited from parent classes and owned by itself).

Rules:

  • Fields of the same width are always assigned together
  • Variables defined in a parent class appear before subclasses
  • If the CompactFields parameter is true (the default) : the narrow variables of the subclass may be inserted into the gap of the parent class variable.
Customer{
    int id=1001;
    string name;
    Account acct;
    {
        name=Anonymous Client;
    }
    public Customer(a){
        acct=new Account();
    }
}
Account{}
Test{
    main(){
        Customer c=ust=newCustomer(); }}Copy the code

3.4 Object Access Positioning

How does a JVM access an object instance inside a stack frame via an object reference in the stack frame?

There are two main ways to access objects:

  • Handle access:

  • Direct Pointers (used by Hotspot) :