Preface
In Java programming, the creation and destruction of objects are basic and critical operations. A deep understanding of this process helps write efficient and stable code. The following will explain the creation and destruction process of objects in Java in detail.
Object creation process
1. Class load check
When used in the codenew
When creating an object with keywords, the Java virtual machine (JVM) will first check whether the corresponding class of the object has been loaded into memory. If it has not been loaded, the JVM will load the bytecode file of the class into memory through the class loader, and verify, prepare and parse it, and finally complete the initialization of the class. For example, when executingPerson person = new Person();
When the JVM will confirm firstPerson
Whether the class is loaded.
2. Allocate memory
After the class loads, the JVM allocates memory space for the new object. There are two main ways to allocate memory:
- Pointer collision: Suppose the memory in the Java heap is regular, all used memory is placed on one side, free memory is placed on the other side, and a pointer is placed in the middle as an indicator of the dividing point. Then the allocated memory is simply to move the pointer to the free space for a distance equal to the object size. This allocation method is called "Bump the Pointer".
- Free list: If the memory in the Java heap is not regular, and the used memory and free memory are interleaved, there is no way to simply collide pointers. The virtual machine must maintain a list to record which memory blocks are available, find a large enough space from the list to allocate it to the object instance, and update the records on the list. This allocation method is called "free list".
Which allocation method to choose 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 the ability to compress and organize space.
3. Initialize the zero value
After the memory allocation is completed, the JVM will initialize the allocated memory space to zero (excluding object headers). This step ensures that the instance fields of the object can be used directly in Java code without assigning the initial value, and the program can access the zero value corresponding to the data types of these fields. For example,int
The initial value of the field of type is 0.boolean
The initial value of the field of type isfalse
。
4. Set object header
The JVM will make necessary settings for the object, such as which class instance the object is, how to find the metadata information of the class, the hash code of the object, the GC generation age of the object, and other information. This information is stored in the object header of the object.
5. Executeinit
method
After all the above work is completed, from the perspective of Java programs, objects have been generated, but from the perspective of JVM, object creation has just begun—<init>
The method has not been executed yet, and all fields are still zero. So generally speaking (by whether the bytecode is followed?invokespecial
Decided by the instruction), executenew
The instruction will be executed later<init>
Method: Initialize the object according to the programmer's wishes, so that a truly available object can be considered completely constructed.
Object destruction process
1. Accessibility analysis
In Java, the destruction of objects is mainly handled by the garbage collection mechanism (GC). The JVM will use the accessibility analysis algorithm to determine whether the object survives. The algorithm starts with a series of objects called "GC Roots" and starts from these nodes to search downward. The paths searched through are called reference chains. When an object is connected to GC Roots without any reference chains, it is proved that the object is unreachable and may be recycled. Common GC Roots include:
- Object referenced in the virtual machine stack (local variable table in the stack frame).
- Object referenced by the static attribute of the class in the method area.
- Object referenced by constants in the method area.
- Objects referenced by JNI (which is commonly referred to as Native method) in the local method stack.
2. First mark
When the object is judged to be unreachable, it is marked for the first time. But at this time the object will not be recycled immediately, but will be placed in a name calledF - Queue
in the queue, and a low-priority thread executes the object in the queuefinalize()
Method (if the object overrides the method).
3. Finalize() method execution
finalize()
The method is the last chance for the object to escape the fate of death. In this method, the object can re-associate with any object on the reference chain, for example (this
Keyword) Assign value to a class variable or member variable of an object. If the object isfinalize()
The method successfully saves itself, and when it is marked the second time, it will be removed from the "recycled" collection; if the object does not escape, it will basically be recycled. But it should be noted thatfinalize()
The execution of the method is unreliable, and the JVM does not guarantee that the method will be executed.
4. Second mark
If the object isfinalize()
After the method is executed, no reference relationship is established with GC Roots, and it will be marked a second time. Objects marked the second time will be truly included in the collection of recyclable objects.
5. Garbage recycling
When the garbage collector performs a garbage collection operation, it recycles the memory space occupied by the objects marked second time and releases it back into the Java heap for subsequent allocation of new objects. Different garbage collectors use different algorithms and strategies to perform garbage collection, such as mark-clearing algorithms, mark-tidying algorithms, copying algorithms, etc.
Knowledge Supplement:
In the heap area of a Java virtual machine, each object may be in one of the following three states.
1) Touchable state: When an object is created, as long as there are reference variables in the program to reference it, it will always be in a touchable state.
2) Resurrectable state: When the program no longer has any reference variables referencing the object, the object enters the resurrectable state. In this state, the garbage collector is ready to release the memory it occupies. Before it is released, it will call the finalize() method of it and other resurrectable objects. These finalize() methods may cause the object to return to the accessible state.
3) Untouchable state: When the Java virtual machine executes the finalize() method of all resurrectable objects, if none of these methods make the object go to the accessible state, the garbage collector will truly recycle the memory it occupies.
Summarize
This is the end of this article about the creation and destruction process of objects in Java. For more related content on creating and destructing Java objects, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!