当前位置:网站首页>Creation of JVM family objects

Creation of JVM family objects

2022-07-04 19:42:00 a_ ittle_ pan

Start writing

“ Never tire of learning , be tireless in teaching others ”

 Insert picture description here

Reference books :“ In depth understanding of java virtual machine ”

personal java Knowledge Sharing Project ——gitee Address

personal java Knowledge Sharing Project ——github Address

Object creation

Case code :

public static void main(String[] args) {
    
		Object o = new Object();
	}

Decompile (javap -c ApplicationContextStarter.class) The result :

public class com.disaster.ApplicationContextStarter {
    
  public com.disaster.ApplicationContextStarter();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class java/lang/Object
       3: dup
       4: invokespecial #1                  // Method java/lang/Object."<init>":()V
       7: astore_1
       8: return
}

Analyze the whole object creation process through cases , analysis main Method (ApplicationContextStarter() It's the constructor method , We haven't been here to pay more attention ):

1. When java The virtual machine encountered bytecode new When the command , First, I will check whether the parameters of this instruction can be in the constant pool ( Method area ) To locate a symbolic reference to a class , And check whether the class represented by this symbol reference has been loaded 、 Parsed and initialized . without , The corresponding class loading process must be performed first ( Previous blogs have talked about ), In the case new Keywords trigger Object The initialization process of is the same as that in the above figure invokespecial Instructions (dup Instructions : Copy the top value on the operand stack , And push the duplicate value onto the operand stack . Unless the value is a category 1 Calculate the value of type , Otherwise, do not use dup Instructions ).

Another thing to note here is the class initialization opportunity in the class loading mechanism , This content is not mentioned in the class loading series ( Personally, I think it will be easier to explain with cases here ), So here is a description .

jvm The specification strictly stipulates that there are four cases that must be initialized , For these four cases, the original text is described as follows :

  1. encounter new、getstatic、putstatic or invokestatic this 4 When there are bytecode instructions , If the class has not been initialized , You need to trigger its initialization first . Generate this 4 The most common instructions are java The code scenario is : Use new When the keyword instantiates an object 、 Read or set the static fields of a class ( By final modification 、 Except for static fields that have been put into the constant pool at compile time ) When , And when calling static methods of a class .
  2. Use java.lang.reflect When a package's method makes a reflection call to a class , If the class has not been initialized , You need to trigger its initialization first .
  3. When initializing a class , If it is found that its parent class has not been initialized , You need to trigger the initialization of its parent class first
  4. When the virtual machine starts , The user needs to specify a main class to execute ( contain main() Method type ), Virtual opportunity initializes the main class first

2. After class loading passes , Next, the virtual machine allocates memory for new objects . The memory size required by the object can be determined after the class is loaded ( Memory layout of objects , The size here is determined by jvm complete )

3. After the object size is determined, start allocating heap memory ,jvm There are two ways to allocate memory for objects , Choose the distribution method by java Whether the pile is regular or not , and java Whether the heap is regular depends on whether the garbage collector used has the function of compression and collation , Here are two memory allocation schemes :

  1. Pointer collision
    If memory is regular , So the virtual machine will use the pointer collision method (Bump The Pointer) To allocate memory for objects ), It means that all used memory is on one side , The free memory is on the other side , There is a pointer in the middle as an indicator of the dividing point , To allocate memory is to move the pointer to the idle side by a distance equal to the size of the object . If the garbage collector chooses something Serial、ParNew This compression algorithm is based on , Virtual machines are distributed in this way . Generally used with compact( Arrangement ) Process collector , Use pointer collisions )
     Insert picture description here

  2. Maintain a list
    If memory is not regular , Used and unused memory interlace with each other , Then the virtual machine will use the free list method to allocate memory for objects . The virtual machine maintains a list , Record which memory blocks are available , When redistributing, find a large enough control in the list to divide it into object instances , And update the list . This distribution becomes “ Free list (Free List)”
     Insert picture description here

4. There is another problem to consider during the allocation of memory by objects : Object creation is a very frequent behavior in virtual machines , Even if you just change the position that a pointer points to , In the case of concurrency, it is not thread safe , There may be an object being given A Allocate memory , The pointer hasn't been modified yet , object B It also USES the original pointer to allocate memory . There are two alternative solutions to this problem :

  1. use CAS Add failure enrichment to ensure the atomicity of updates
  2. Each thread is pre allocated a block TLAB– adopt -XX:+/-UserTLAB Parameter to set ( Mentioned in previous articles , At that time, we can issue a special issue to explain TLAB)

5. After the memory allocation is complete , The memory space that the virtual machine must allocate to ( Object headers are not included ) All initialized to zero , If used TLAB Words , This work can also be advanced to TLAB By the way . This operation ensures that the instance of the object is in java Code can be used directly without initial value , Enables the program to access the zero values corresponding to the data types of these fields .

6. After the assignment operation , The virtual machine also needs to make the necessary settings for the objects , The class that the object belongs to ( That is, the metadata information of the class )、 Object's HashCode And objects GC Information 、 Data such as lock information is stored in the object header of the object . How this process is set depends on JVM Realization

7. perform init Method : After the above steps are completed , From the perspective of virtual machine , A new object has been created . But from Java From a procedural perspective , Object creation just started – Constructors ( namely Class In the document < init >() The method has not been implemented yet ), All fields are zero by default , Other resources and state information required by the object have not been constructed according to the specified intention . Generally speaking ,new Execution will be followed by execution < init >() Method ( When using new Keywords will be followed when creating objects () The method is the case class In the figure invokespecial Instructions ). At this point, a really usable object can be constructed .

8. structure Object After the object is finished, pass astore_1 The instruction assigns the memory address of the object to o Variable

The above content is from jvm From the perspective of memory, explain the object allocation , From the perspective of garbage collection, it is roughly as shown in the following figure ( We need to distinguish the process of these two perspectives );
 Insert picture description here

原网站

版权声明
本文为[a_ ittle_ pan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041810495988.html