Chapter 10 Object Instantiation Memory Layout and Access Location

Chapter 10 Object Instantiation Memory Layout and Access Location

JVM explained by Song Hongkang from Shang Silicon Valley: bilibili link

1 Instantiation of objects

  • Interview questions
    • Meituan
      • How are objects stored in the JVM?
      • What's in the object header information?
    • Ant Financial
      • The second side: what's in the java object header?

Insert picture description here

Insert picture description here


  • Steps to create an object

    1. Determine whether the class corresponding to the object is loaded, linked, initialized

      When the virtual machine encounters a new instruction, it first checks whether the parameter of this instruction can locate a symbol reference of a class in the constant pool of Metaspace, and checks whether the class represented by this symbol reference has been loaded, parsed, and initialized. (That is, determine whether the class meta information exists). If not, then in the parental delegation mode, use the current class loader to find the corresponding .class file with ClassLoader+package name+class name Key. If the file is not found, a ClassNotFoundException will be thrown. If it is found, the class will be loaded and the corresponding Classs object will be generated.

    2. Allocate memory for the object

      First calculate the space occupied by the object, and then allocate a block of memory in the heap for the new object. If the instance member variable is a reference variable, just allocate the reference variable space, which is 4 bytes in size.

      • If the memory is regular, use pointer collision

        If the memory is regular, the virtual machine will use Bump The Pointer to allocate memory for the object. It means that all the used memory is on one side, and the free memory is on the other side. There is a pointer in the middle as an indicator of the demarcation point. Allocating memory is just moving the pointer to the free side by a distance equal to the size of the object. If the garbage collector chooses Serial and ParNew based on the mark-compression algorithm, the virtual machine uses this allocation method. Generally, when using a collector with a compact process, pointer collision is used.

      • If the memory is not regular, the virtual machine needs to maintain a list and use the free list to allocate

        If the memory is not regular, the used memory and the unused memory are interleaved with each other, then the virtual machine will use the free list method to allocate memory for the object. It means that the virtual machine maintains a list to record which memory blocks are available. When redistributing, find a large enough space from the list to divide the object instance and update the content on the list. This allocation method is called "Free List".

        Note : The choice of allocation method is determined by whether the Java heap is regular, and whether the Java heap is regular is determined by whether the garbage collector used has a compression function.

    3. Dealing with concurrency security issues

      When allocating memory space, another problem is to ensure the thread safety of new objects in time: creating objects is a very frequent operation, and the virtual machine needs to solve the problem of concurrency safety. The virtual machine uses two methods to solve the concurrency security problem:

      • CAS (Compare And Swap) failure retry, area lock: to ensure the atomicity of the pointer update operation;
      • TLAB right action in accordance with the memory allocation is divided among different threads of space that each thread a small piece of pre-allocated heap memory in Java, called thread-local allocation buffer (TLAB, Thread Local Allocation Buffer) , a virtual machine Whether to use TLAB or not can be set by the -XX:+/-UseTLAB parameter.
    4. Initialize the allocated space

      After the memory allocation is over, the memory space allocated by the virtual machine is initialized to a value of zero (excluding the object header). This step ensures that the instance fields of the object can be used directly in the Java code without assigning initial values, and the program can access the zero values ​​corresponding to the data types of these fields.

    5. Set the object header of the object

      Store the object's class (that is, the class's metadata information), the object's HashCode, the object's GC information, lock information and other data in the object's object header. The specific setting of this process depends on the JVM implementation.

    6. Execute the init method to initialize

      From the point of view of a Java program, initialization has only officially begun. Initialize the member variables, execute the instantiated code block, call the construction method of the class, and assign the first address of the object in the heap to the reference variable.

      Therefore, generally speaking (determined by whether the bytecode is followed by the invokespecial instruction), the execution method will follow after the new instruction. The object is initialized according to the programmer's wishes, so that a truly usable object is completely created.

2 The memory layout of the object

  • What content does the created object contain in the heap

    Insert picture description here

    Not all objects save type pointers

  • example

    /**
     * 测试对象实例化的过程
     *  ① 加载类元信息 - ② 为对象分配内存 - ③ 处理并发问题  - ④ 属性的默认初始化(零值初始化)
     *  - ⑤ 设置对象头的信息 - ⑥ 属性的显式初始化、代码块中初始化、构造器中初始化
     *
     *
     *  给对象的属性赋值的操作:
     *  ① 属性的默认初始化 - ② 显式初始化 / ③ 代码块中初始化 - ④ 构造器中初始化
     */
    
    public class Customer{
          
          
        int id = 1001;  // ② 显式初始化
        String name;
        Account acct;
    
        {
          
          
            name = "匿名客户";  // ③ 代码块中初始化
        }
        public Customer(){
          
          
            acct = new Account();  // ④ 构造器中初始化
        }
    
    }
    class Account{
          
          
    
    }
    
    public class CustomerTest {
          
          
        public static void main(String[] args) {
          
          
            Customer cust = new Customer();
        }
    }
    

    Insert picture description here

3 Access location of the object

Insert picture description here

  • How does the JVM access its internal object instances through the object references in the stack frame?

    • Access by reference on the stack

    Insert picture description here

  • Two ways of object access

    • Handle access

      Insert picture description here

      • Advantages: only need to change the address in the handle pool after GC
      • Disadvantages: low access efficiency, access to instance data and metadata requires a transfer
    • Direct pointer (adopted by Hotspot)

      Insert picture description here

      Advantages: high access efficiency, access to instance data in one step

      Disadvantages: After GC, the reference address in the local variable table in the virtual machine stack needs to be changed

Guess you like

Origin blog.csdn.net/weixin_42638946/article/details/113646905