当前位置:网站首页>< 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

边栏推荐
- 面试突击58:truncate、delete和drop的6大区别!
- 缺失值處理
- A classmate asked what framework PHP should learn?
- . Net release and support plan introduction
- Huawei cloud "digital intelligence" operation and maintenance
- Graduation season · undergraduate graduation thoughts -- the self-help road of mechanical er
- docker: Error response from daemon: Conflict. The container name “/mysql“ is already in use by conta
- Donghua University - Research on interpretable recommendation micro behavior with enhanced knowledge perception reasoning
- 内容推荐流程
- [applet project development -- Jingdong Mall] subcontracting configuration of uni app development
猜你喜欢

Content recommendation process

"Half of Zhejiang's Venture Capital Circle" must be state-owned assets

Database industry analysis: from the global IT industry trend to the development of domestic databases
![Azkaban startup error 2022/06/20 21:39:27.726 +0800 error [stdouterrredirect] [azkaban] exception in thread](/img/02/2e402f05022b36dc48ff47232e8535.png)
Azkaban startup error 2022/06/20 21:39:27.726 +0800 error [stdouterrredirect] [azkaban] exception in thread "m

Hello playwright: (7) simulate keyboard and mouse

Correct method of converting Inkscape into DXF file SVG exporting DXF file

轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷

. Net release and support plan introduction

Behind the fall of the first Seberg: the extreme race between technology and frostbite

中国移动手机用户缓慢增长,但努力争取高利润的5G套餐用户
随机推荐
Grafana 9 正式发布,更易用,更酷炫了!
Principle of synchronized implementation
. Net release and support plan introduction
各位大佬,第一次使用flink mysql cdc, 现在程序启动 没报错 新增数据没有打印出来
SaaS application development guide
Quickly master asp Net authentication framework identity - user registration
数据库行业分析:从全球IT产业趋势到国产数据库发展之路
Configuration of development environment for JSP learning
RF Analyzer Demo搭建
STM32系列(HAL库)——F103C8T6硬件SPI点亮带字库OLED屏
MTLs guidelines for kubernetes engineers
Using stream API instead of SQL
Database industry analysis: from the global IT industry trend to the development of domestic databases
Stop automatically after MySQL server starts
Come to Xiamen! Online communication quota free registration
【工具】pip和conda的相关使用
mysql服务器启动后自动停止
Quartus Prime 18.0软件安装包和安装教程
Parallel integrates with moonbeam through xcm, bringing para and defi use cases into moonbeam ecology
Nuxt - create nuxt app