当前位置:网站首页>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 );
边栏推荐
猜你喜欢
PointNeXt:通过改进的模型训练和缩放策略审视PointNet++
How to use async Awati asynchronous task processing instead of backgroundworker?
Detailed explanation of the binary processing function threshold() of opencv
联想首次详解绿色智城数字孪生平台 破解城市双碳升级难点
92.(cesium篇)cesium楼栋分层
多表操作-内连接查询
黑马程序员-软件测试--09阶段2-linux和数据库-31-43修改文件权限字母发的说明,-查找链接修改文件,查找文件命令,链接文件,压缩解压方式,vi编辑器基本使用,
BCG 使用之新建向导效果
JVM系列之对象的创建
在线文本行固定长度填充工具
随机推荐
【毕业季】绿蚁新醅酒,红泥小火炉。晚来天欲雪,能饮一杯无?
勾股数规律(任意三个数能够满足勾股定理需要满足的条件)
Master the use of auto analyze in data warehouse
Functional interface
Crawler (6) - Web page data parsing (2) | the use of beautifulsoup4 in Crawlers
Educational Codeforces Round 22 E. Army Creation
Allure of pytest visual test report
《工作、消费主义和新穷人》的微信读书笔记
Niuke Xiaobai monthly race 7 I new Microsoft Office Word document
Matrix flip (array simulation)
There are multiple divs in the large div, which are displayed on the same line. After overflow, scroll bars are generated without line breaks
FTP, SFTP file transfer
Shell 編程核心技術《四》
Shell programming core technology "three"
Shell programming core technology II
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
English grammar_ Noun - use
How test engineers "attack the city" (Part I)
Educational Codeforces Round 22 E. Army Creation
Chrome开发工具:VMxxx文件是什么鬼