In the JVM runtime space, the entire lifecycle of an object can be roughly divided into 7 phases: the creation phase (creation), the application phase (using), the invisible phase (invisible), the unreachable phase (unreachable), the collection phase (collected) , the end stage (finalized) and the release phase (free). These 7 phases above constitute the complete lifecycle of the objects in the JVM. The following describes the different situations where the object is in these 7 phases.
Create phase
In the object creation phase, the system completes the creation of the object through the following steps:
(1) Allocate storage space for objects.
(2) Start constructing the object.
(3) Recursive invocation of its superclass construction method.
(4) Initialization of object instance and initialization of variables.
(5) Executing the construction method body.
The 3rd step in the 5 steps above is to recursively invoke the constructor of all the parent classes extended by the class, and a Java class (except the object class) has at least one parent class (object), which is both mandatory and implicit. You may have noticed that when you create a Java class, you do not explicitly declare an object parent class for the extension (extends). In fact, in Java programming, any Java class is directly or indirectly a subclass of the object class. For example, the following code:
public class A {
…
}
这个声明等同于下面的声明:
public class A extends java.lang.Object {
…
}
This explains some of the processing work that the system does when the object is in the creation phase, some of which are closely related to the performance of the application, so when creating objects, we should follow some basic rules to improve the performance of the application.
Here are a few key application rules when creating objects:
(1) Avoid creating objects in the loop body, even if the object occupies little memory space.
(2) Make the object conform to the garbage collection standard as promptly as possible.
(3) Do not use too deep inheritance level.
(4) Accessing a local variable is better than accessing a variable in a class.
About rules (1) Avoid creating objects in the loop body, even if the object takes up little memory space, you need to be prompted that this situation is often encountered in our practical applications, and we can easily make similar mistakes, such as the following code:
… …
for (int i = 0; i < 10000; ++i) {
Object obj = new Object();
System.out.println("obj= "+ obj);
}
… …
The code above is written in a way that is not unfamiliar to you, you might have done the same thing in previous applications, especially when enumerating object elements in a vector object, but this is a violation of the rule (1) because it wastes a lot of memory space, and the correct way As shown below:
… …
Object obj = null;
for (int i = 0; i < 10000; ++i) {
obj = new Object();
System.out.println("obj= "+ obj);
}
… …