当前位置:网站首页>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 ”
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 :
- 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 .
- 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 .
- 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
- 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 :
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 )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)”
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 :
- use CAS Add failure enrichment to ensure the atomicity of updates
- 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 );
边栏推荐
猜你喜欢
牛客小白月赛7 谁是神箭手
MySQL数据库基本操作-DDL | 黑马程序员
Explore the contour drawing function drawcontours() of OpenCV in detail with practical examples
Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
Siemens HMI download prompts lack of panel image solution
How to use async Awati asynchronous task processing instead of backgroundworker?
Niuke Xiaobai month race 7 who is the divine Archer
The explain statement in MySQL queries whether SQL is indexed, and several types in extra collate and summarize
abc229 总结(区间最长连续字符 图的联通分量计数)
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
随机推荐
HDU 6440 2018中国大学生程序设计网络选拔赛
HDU 1372 & POJ 2243 Knight moves (breadth first search)
HDU 1372 & POJ 2243 Knight Moves(广度优先搜索)
Add namespace declaration
SSRS筛选器的IN运算(即包含于)用法
The difference and usage between substr (), slice (), and substring () in the string interception methods of "understand series after reading"
Stream stream
TCP waves twice, have you seen it? What about four handshakes?
Chrome开发工具:VMxxx文件是什么鬼
To sort out messy header files, I use include what you use
Pointnet/Pointnet++点云数据集处理并训练
牛客小白月赛7 谁是神箭手
明明的随机数
测试工程师如何“攻城”(上)
socket编程demo二
BCG 使用之CBCGPProgressDlgCtrl进度条使用
How to use async Awati asynchronous task processing instead of backgroundworker?
需求开发思考
Lm10 cosine wave homeopathic grid strategy
Cbcgpprogressdlg progress bar used by BCG