当前位置:网站首页>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 );
边栏推荐
- Shell 编程核心技术《二》
- SSRS筛选器的IN运算(即包含于)用法
- C# 使用StopWatch测量程序运行时间
- Hough transform Hough transform principle
- How to use async Awati asynchronous task processing instead of backgroundworker?
- 项目中遇到的线上数据迁移方案1---总体思路整理和技术梳理
- Upgrade the smart switch, how much is the difference between the "zero fire version" and "single fire" wiring methods?
- Oracle with as ORA-00903: invalid table name 多表报错
- Some thoughts on whether the judgment point is located in the contour
- Shell 编程核心技术《三》
猜你喜欢
如何使用Async-Awati异步任務處理代替BackgroundWorker?
黑马程序员-软件测试--09阶段2-linux和数据库-31-43修改文件权限字母发的说明,-查找链接修改文件,查找文件命令,链接文件,压缩解压方式,vi编辑器基本使用,
English语法_名词 - 使用
Swagger突然发癫
勾股数规律(任意三个数能够满足勾股定理需要满足的条件)
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
一文掌握数仓中auto analyze的使用
C# 使用StopWatch测量程序运行时间
MySQL数据库基本操作-DDL | 黑马程序员
如何使用Async-Awati异步任务处理代替BackgroundWorker?
随机推荐
BCG 使用之CBCGPProgressDlg进度条使用
YOLOv5s-ShuffleNetV2
C# 使用StopWatch测量程序运行时间
线上数据库迁移的几种方法
Generate XML elements
Shell programming core technology "I"
Niuke Xiaobai month race 7 e applese's super ability
Shell 编程核心技术《一》
Opencv functions and methods related to binary threshold processing are summarized for comparison and use
Stream stream
Specify the character set to output
mysql中explain语句查询sql是否走索引,extra中的几种类型整理汇总
Reflection (I)
在线文本行固定长度填充工具
1011 World Cup Betting (20 分)(PAT甲级)
Online data migration scheme encountered in the project 1 - general idea sorting and technical sorting
牛客小白月赛7 I 新建 Microsoft Office Word 文档
《工作、消费主义和新穷人》的微信读书笔记
HDU 1372 & POJ 2243 Knight moves (breadth first search)
To sort out messy header files, I use include what you use