[JVM] Ten. Object instantiation, memory layout and access location

Hello, everyone, I am a pig who is dominated by cabbage.

A person who loves to study, sleepless and forgets to eat, is obsessed with the girl's chic, calm and indifferent coding handsome boy.

If you like my text, please follow the public account "Let go of this cabbage and let me come".

10- Object instantiation, memory layout and access positioning

One, the instantiation of the object

Insert picture description here

Methods of creating objects

  1. new, use the new keyword, call static method creation in singleton mode, create by builder mode and factory mode (xxxBuilder, xxxFactory)
  2. Through reflection, the newInstance() of Class can only call the constructor without parameters, and the access modifier must be public
  3. Also through reflection, the newInstance (xxx) of the Constructor can have no or can have parameters, and there is no restriction on access control characters
  4. clone(): Without any constructor, the current class implements the Cloneable interface and implements clone()
  5. Use deserialization to create objects, and obtain binary streams through files and networks to deserialize and create objects
  6. Use third-party libraries to create objects

Steps to create an object

  1. Determine whether the class corresponding to the object is loaded, linked (verified, prepared, parsed), 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, to determine whether the 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 Class object will be generated.

  2. Allocate memory for the object

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

    • If the memory is regular, then the virtual machine will use the pointer collision method (Bump The Pointer) to allocate memory for the object.

      This means that all used memory is on one side, and the space memory is on the other side. A pointer is placed in the middle as an indicator of the dividing 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 compression algorithms, 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 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 of which memory blocks are available, and finds a large enough space from the list to divide the object instance from the list and update the content on the list. This allocation method is called "Free List (Free List)".

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

  3. Deal with concurrency security issues .

    Use CAS with failed retry to ensure the atomicity of the update, or allocate a TLAB in advance for each thread.

  4. Initialize the allocated space

    All properties are set to default values ​​to ensure that the object instance fields can be used directly without assigning values.

  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 for initialization , mainly display initialization, code block initialization, and constructor initialization

    From the perspective 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.

    So in general (determined by whether the bytecode is followed by the invokespecial instruction), after the new instruction, there will be an execution method, which initializes the object according to the programmer's wishes, so that a truly usable object is completely created.

Second, the memory layout of the object

Insert picture description here

What about the distribution of an object in the heap memory? It mainly includes the object header, instance data, and alignment padding.

Header

The object header contains two parts of information: runtime metadata and type pointer

Runtime metadata (Mark Word) mainly includes hash value (HashCode), GC generation age, lock status flag, lock held by thread, biased thread ID, biased timestamp

The type pointer points to the metadata InstanceKlass to determine the type of the object

Note: If it is an array, you also need to record the length of the array.

Instance data

It is the effective information that the object is storing, including various types of fields defined in the program code (including fields inherited from the parent class and owned by itself)

rule:

  • Fields of the same width are always allocated together
  • Variables defined in the parent class will appear before the child class
  • If the CompactFields parameter is true (the default is true): the narrow variables of the subclass may be inserted into the gap of the parent variable

Object filling

It is not necessary, and has no special meaning, only serves as a placeholder

Icon

This picture is really awesome and awesome. It’s too clear. When I look at it, I have solved all the doubts in my mind. Remembering this picture is almost the content of this chapter.

Insert picture description here

Third, the access location of the object

Insert picture description here

Icon

Insert picture description here

  • The purpose of creating an object is to use it

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

Object access method

Handle access

Insert picture description here

Handle access needs to open up a space, first access the handle, and then access the object type data through the handle pool, the access efficiency is relatively low

Benefit: The reference stores the stable handle address. When the object is moved (moving objects during garbage collection is common), only the instance data pointer in the handle can be changed, and the reference itself does not need to be modified.

Direct pointer (adopted by HotSpot)

Insert picture description here

More efficient access


notes:

The operation of assigning values ​​to the properties of the object:

1. Default initialization of attributes

2. Explicit initialization

3. Initialization in the code block

4. Initialization in the constructor

2/3/4 in

Object instantiation process

1. Load class meta information

2. Allocate memory for the object

3. Deal with concurrency issues

4. Default initialization of attributes (zero value initialization)

5. Set the information of the object header

6. Display initialization of attributes, initialization in code block, initialization in constructor

new Object() is like a dough maker, new is the shape coming out, Object() is like coloring

Guess you like

Origin blog.csdn.net/weixin_44226263/article/details/112400884