当前位置:网站首页>< JVM part I: memory and garbage collection part > 08 object instantiation and direct memory
< JVM part I: memory and garbage collection part > 08 object instantiation and direct memory
2022-06-22 18:06:00 【Big plums that love programming】
Blog's front page : Big plum who loves programming
️ Column home page :JVM From entry to mastery
The purpose of the article : Song Hongkang in Silicon Valley JVM A full set of tutorialBloggers in the learning stage , If problems are found , Please inform , Thank you very much
At the same time, thank you very much for your support
One word a day : I am nothing but mortal , You can turn your heart to the sky .
thank : I just stand on the shoulders of giants and organize this article , Thanks to the big guys who are ahead !
Last , I wish you all a little progress every day ! Welcome to like the collection ️ Comments support bloggers !
️ ️ Last article -<JVM Part 1 : Memory and garbage collection >07- Method area ️ ️

List of articles
- 8. Object instantiation and direct memory
- 8.1. Object instantiation
- 8.1.1. How to create objects
- 8.1.2. To create an object
- 1. Determine whether the class corresponding to the object is loaded 、 link 、 initialization
- 2. Allocate memory for objects
- 3. Dealing with concurrency
- 4. Initialize the memory allocated to ( Assign default initial value )
- 5. Set the object header of the object
- 6. perform init Method to initialize
- summary
- 8.2. Object memory layout
- 8.3. Object access location
- 8.4. Direct memory (Direct Memory)
8. Object instantiation and direct memory
8.1. Object instantiation
Interview questions
Meituan :
The object is JVM How is it stored in ?
What's in the object header ?
The ant gold dress :
Java What's in the head of the object ?
8.1.1. How to create objects

Code demonstration
/** * @author shkstart [email protected] * @create 2020 17:16 */
public class ObjectTest {
public static void main(String[] args) {
Object obj = new Object();
}
}
Result analysis

8.1.2. To create an object
As mentioned above, we look at the creation process of objects from the perspective of bytecode , Now, from the perspective of execution steps :

1. Determine whether the class corresponding to the object is loaded 、 link 、 initialization
Virtual opportunity to a new Instructions , First of all, check whether the parameters of this instruction are in Metaspace A symbolic reference to a class is located in the constant pool of , Also check whether the class represented by the symbol reference has been loaded , Parse and initialize ( That is, to judge whether class meta information exists ).
without , So in the parental delegation mode , Use the current classloader to ClassLoader + Package name + Class called key Search for the corresponding .class file ;
- If no files are found , Throw out ClassNotFoundException abnormal
- If you find , Then load the class , And generate the corresponding Class object
2. Allocate memory for objects
First, calculate the size of the space occupied by the object , Then divide a block of memory in the heap for the new object . If the instance member variable is a reference variable , Just allocate reference variable space , namely 4 Byte size ( Reference variables save only references , So the size can be determined , The size of non reference variables is fixed .)
If memory is regular : The virtual machine will adopt Pointer collision method (Bump The Point) To allocate memory for objects .
- It means that all used memory is on one side , Free memory 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 is Serial ,ParNew This compression algorithm is based on , Virtual machines are distributed in this way . Generally use the belt Compact( Arrangement ) Process collector , Use pointer collisions .

If the memory is out of order : The virtual machine needs to maintain a Free list (Free List) To allocate memory for objects .
- Used and unused memory interlace with each other , Then the virtual machine will use the free list to allocate memory for objects . The virtual machine maintains a list , The memory blocks on the record are available , At the time of allocation, find a large enough space from the list to divide it into object instances , And update the list .
Select which allocation method is determined by Java Whether the pile is regular or not depends on , and Java Whether the heap is regular or not depends on whether the garbage collector is equipped with compression and sorting function .
3. Dealing with concurrency
- use CAS( spinlocks ) Failure to retry 、 Region locking guarantees the atomicity of updates
- Each thread is pre allocated a block TLAB: By setting
-XX:+UseTLABParameters to set
4. Initialize the memory allocated to ( Assign default initial value )
All properties set default values , Ensure that the object instance field can be used directly without assignment
** give an example :** For basic data types byte,short,int,long,float,double by 0, The boolean type is false, The reference type defaults to NULL
5. Set the object header of the object
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 .
6. perform init Method to initialize
stay Java From a procedural perspective , Initialization just started . Initialize member variables , Execute instantiation code block , Call the constructor of the class , The first address of the object in the heap is assigned to the reference variable .
So in general ( Followed by bytecode invokespecial Determined by the order ),new The instruction is followed by the execution of the constructor , Initialize the object according to the programmer's wishes , Such a really usable object is created .
Add : The operation of assigning values to object properties
① Property ( The first 4 Step ) - ② Explicitly initialize / ③ Initialization in the code block / ④ Initialization in constructor
/** * * The operation of assigning values to the properties of an object : * ① Property - ② Explicitly initialize / ③ Initialization in the code block - ④ Initialization in constructor Distinguish between the following two types of constructors <client> class constructor : Static data initialization <init> Instance builder : Initialization of non static data * @author shkstart [email protected] * @create 2020 17:58 */
public class Customer{
int id = 1001;
String name;
Account acct;
{
name = " Anonymous clients ";
}
public Customer(){
acct = new Account();
}
}
class Account{
}
Display initialization 、 Code block initialization 、 Initialization in the constructor is done in the method

summary
Object instantiation process
- Loading class meta information
- Allocate memory for objects
- Dealing with concurrency
- Property ( Zero initialization )
- Set object header information
- Property display initialization 、 Initialization in the code block 、 Initialization in constructor
8.2. Object memory layout

8.2.1. Object head (Header)
The object header consists of two parts , Namely Runtime metadata (Mark Word) and Type a pointer . If it's an array , You also need to record the length of the array
Runtime metadata
- Hash value (HashCode)
- GC Generational age
- Lock status flag
- A lock held by a thread
- To the thread ID
- Time stamp
Type a pointer
Point to class metadata InstanceKlass, Determine the type the object belongs to .
8.2.2. The instance data (Instance Data)
It's the valid information that the object really stores , Includes various types of fields defined in program code ( Including fields inherited from the parent class and owned by itself )
- Fields of the same width are always assigned together
- Variables defined in the parent class appear before the subclass
- If CompactFields Parameter is true( The default is true): Narrow variables of a subclass may be inserted into the gap of a parent variable
8.2.3. Alignment filling (Padding)
It's not necessary , It doesn't mean anything , It's just a place holder
give an example
public class Customer{
int id = 1001;
String name;
Account acct;
{
name = " Anonymous clients ";
}
public Customer() {
acct = new Account();
}
}
public class CustomerTest{
public static void main(string[] args){
Customer cust=new Customer();
}
}
Icon

Summary

8.3. Object access location

JVM How to access the internal object instance through the object reference in the stack frame ?

8.3.1. Handle access

advantage : reference Store the stable handle address in , Objects are moved ( Moving objects is common in garbage collection ) Only the instance data pointer in the handle will be changed ,reference It doesn't need to be modified
shortcoming : You need to create a special space for the handle pool , Use more space . During the interview , You need to find the handle variable through the stack reference first , Then access the object instance from the handle variable , Low efficiency .
8.3.2. Direct Pointers (HotSpot use )

A direct pointer is a reference in a local variable table , Point directly to an instance in the heap , There are type pointers in object instances , It points to the object type data in the method area
advantage : Local variables in the stack directly refer to instances in the heap , More efficient access . There is no need to open a spatial record handle .
shortcoming : When an object is moved ( Moving objects is common in garbage collection ),reference Will change .
8.4. Direct memory (Direct Memory)
8.4.1. Overview of direct memory
- Not part of the virtual machine runtime data area , Neither 《Java Virtual machine specification 》 Memory area defined in .
- Direct memory is in Java Out of the pile 、 Memory range directly applied to the system .
- originate NIO, By storing... In the heap DirectByteBuffer operation Native Memory .
- Usually , Access to direct memory is faster than Java Pile up , namely High reading and writing performance .
- So for performance reasons , Direct memory may be considered for frequent reading and writing .
- Java Of NIO Library allows Java Programs use direct memory , For data buffers
8.4.2. Indirect cache ( Conventional IO)
Use IO Read and write files , Need to interact with disk , You need to switch from user state to kernel state . In kernel state , Need two copies of memory to store duplicate data , Low efficiency .

8.4.3. Direct cache
Use NIO when , The direct cache that the operating system delimits can be java Code direct access , Only one copy. .NIO Suitable for reading and writing large files .

May also lead to OutOfMemoryError abnormal
Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory
at java.nio.Bits.reserveMemory(Bits.java:693)
at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:311)
at com.atguigu.java.BufferTest2.main(BufferTest2.java:20)
Because of the direct existence of Java Out of pile , So its size is not directly limited to -Xmx The maximum heap size specified , But the system memory is limited ,Java The sum of heap and direct memory is still limited by the maximum memory the operating system can give .
- Higher allocated recovery costs
- Not subject to JVM Memory recovery management
Direct memory size can be determined by MaxDirectMemorySize Set up . If you don't specify , The default is the maximum value of the heap -Xmx Consistent parameter values

边栏推荐
- 轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
- be based on. NETCORE development blog project starblog - (12) razor page dynamic compilation
- 测试组的任务职责和测试的基本概念
- Activity启动流程梳理
- Interview shock 58: Six differences among truncate, delete and drop!
- Database industry analysis: from the global IT industry trend to the development of domestic databases
- clickhouse 21. X cluster four piece one copy deployment
- Source code of live video system, hiding and Title Modification of the top title bar
- A classmate asked what framework PHP should learn?
- math_角函数&反三角函数
猜你喜欢

AD20/Altium designer——过孔盖油

Come to Xiamen! Online communication quota free registration

Ad20/altium Designer - oil for manhole cover

Quartus prime 18.0 software installation package and installation tutorial

Binary tree practice the second bullet

【FPGA+PWM】基于FPGA的三相PWM整流器移相触发电路的设计与实现

Interview shock 58: Six differences among truncate, delete and drop!

I became a big enemy when I bought wanghong ice cream

How can the new generation of HTAP databases be reshaped in the cloud? Tidb V6 online conference will be announced soon!

UI automation positioning edge -xpath actual combat
随机推荐
It may be the most comprehensive Matplotlib visualization tutorial in the whole network
Tasks and responsibilities of the test team and basic concepts of testing
Mqtt of NLog custom target
[small program project development -- Jingdong Mall] rotation chart of uni app development
Heartless sword in Chinese
be based on. NETCORE development blog project starblog - (12) razor page dynamic compilation
SaaS化应用开发指南
Xftp 7(FTP/SFTP客户端) V7.0.0107 官方中文免费正式版(附文件+安装教程)
UI automation positioning edge -xpath actual combat
诺亚财富拟登陆港交所:第一季度业绩大幅下滑,曾踩雷“承兴案”
What is flush software? Is it safe to open a mobile account?
知乎热问:一个程序员的水平能差到什么程度?
来厦门了!线上交流限额免费报名中
云端极简部署Svelte3聊天室
Gridhome, a must-have static site generator for beginners
Pytorch——报错解决:“torch/optim/adamw.py” beta1, UnboundLocalError: local variable ‘beta1‘
Azkaban startup error 2022/06/20 21:39:27.726 +0800 error [stdouterrredirect] [azkaban] exception in thread "m
JSP learning (3) -- JSP implicit object
缺失值處理
Hello playwright: (7) simulate keyboard and mouse