当前位置:网站首页>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 编程核心技术《四》
- Pointnet/Pointnet++点云数据集处理并训练
- Lm10 cosine wave homeopathic grid strategy
- [QNX Hypervisor 2.2用户手册]6.3.1 工厂页和控制页
- [QNX hypervisor 2.2 user manual]6.3.1 factory page and control page
- . Net ORM framework hisql practice - Chapter 2 - using hisql to realize menu management (add, delete, modify and check)
- Siemens HMI download prompts lack of panel image solution
- The page element is vertically and horizontally centered, realizing the vertical and horizontal centering of known or unknown width.
- HDU 1372 & POJ 2243 Knight moves (breadth first search)
- 添加命名空间声明
猜你喜欢
BCG 使用之新建向导效果
Oracle with as ora-00903: invalid table name multi report error
Opencv functions and methods related to binary threshold processing are summarized for comparison and use
西门子HMI下载时提示缺少面板映像解决方案
To sort out messy header files, I use include what you use
Master the use of auto analyze in data warehouse
C# 使用StopWatch测量程序运行时间
JVM系列之对象的创建
C语言-入门-基础-语法-流程控制(七)
如何使用Async-Awati异步任務處理代替BackgroundWorker?
随机推荐
FPGA timing constraint sharing 01_ Brief description of the four steps
Educational Codeforces Round 22 E. Army Creation
1005 spell it right (20 points) (pat a)
线上数据库迁移的几种方法
@transactional滥用导致数据源连接池耗尽问题
勾股数规律(任意三个数能够满足勾股定理需要满足的条件)
Shell 编程核心技术《一》
node_ Exporter deployment
Shell 编程核心技术《三》
An example of multi module collaboration based on NCF
kotlin 继承
socket编程demo二
Chrome开发工具:VMxxx文件是什么鬼
安徽 中安在线文旅频道推出“跟着小编游安徽”系列融媒体产品
Shell programming core technology "three"
HDU 1372 & POJ 2243 Knight Moves(广度优先搜索)
PolyFit软件介绍
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
kotlin 条件控制
函数式接口