当前位置:网站首页>JVM Part 1: memory and garbage collection part 9 - runtime data area - object instantiation, memory layout and access location
JVM Part 1: memory and garbage collection part 9 - runtime data area - object instantiation, memory layout and access location
2022-07-27 05:14:00 【_ Dean_】
JVM Part 1 : Memory and garbage collection Chapter 9 – Run time data area - Object instantiation , Memory layout and access location
1. Object instantiation
1.1 Interview questions of Dachang
- Meituan
- The object is JVM How is it stored in ?
- What's in the object header ?
- The ant gold dress
- Two sides :java What's in the guy's head ?

1.2 How to create objects
new: The most common waydirect new
deformation 1: In a singleton class, call
getInstance Static class methods for/** * @author zr * @date 2022/4/27 16:56 */ public class Singleton { private Singleton() { } //private It can only be accessed within yourself private static Singleton instance = new Singleton();// Define an instance of yourself within yourself public static Singleton getInstance() { // This static method is directly accessible from the outside return instance; } } class Test{ public static void main(String args[]){ Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); if(s1==s2) System.out.println(" This class is singleton mode "); else System.out.println(" This class is not singleton mode "); } }
deformation 2:
XxxBuilder/XxxFactory Static method of
Class Of newInstance Method: The way of reflection , stay JDK9 The inside is markedobsoleteMethods , because Only null argument constructors can be calledConstructor Of newInstance(Xxx): The way of reflection , You can call null parameters 、 Constructors with parameters , Permission is not requiredUse clone(): Do not call any constructors , The current class needs to implement Cloneable Interface , Realization clone()Using deserialization: From file 、 Get the binary stream of an object from the networkThird party LibraryObjenesis
1.3 To create an object
Look at the creation process of objects from the perspective of bytecode
public class ObjectTest { public static void main(String[] args) { Object obj = new Object(); } }
- main( ) The bytecode corresponding to the method ( I'll talk about it later )
- call new After instruction , load Object class ( The following steps 12345)
- call Object Class init( ) Method ( step 6)
0: new #2 // class java/lang/Object 3: dup 4: invokespecial #1 // Method java/lang/Object."<init>":()V 7: astore_1 8: return
Determine whether the class corresponding to the object is loaded 、 link 、 initialization
Virtual opportunity to a new Instructions , First go Check whether the parameters of this instruction can be 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 found in , Then load the class , And generate the corresponding Class Class object
Allocate memory for objects
If memory is regular
Pointer collisionIf memory is regular , Then the virtual machine will adopt
Needle collision method ( Bump The Pointer )To allocate memory for objects . It means that all used memory is on one side , Free memory is on the other side , With a pointer in the middle as the indicator of the dividing point, allocating memory is just moving the pointer to the free side for a distance equal to the size of the object .If the garbage collector chooses is
Serial、ParNewThis compression algorithm is based on , Virtual machines are distributed in this way . Generally used with compact( Arrangement ) Process collector , Use pointer collisions .Tag compression ( Arrangement ) AlgorithmWill defragment memory , Heap memory a memory object , On the other side is the free space .
If the memory is out of order
First, calculate 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 .The virtual machine needs to maintain a list
Free list allocation
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 .
intend The virtual machine maintains a list , Record which memory blocks are available on , During reallocation, find a large enough space from the list to divide it into object instances , And update the list . This distribution becomes “ Free list (Free List ) ".Tag clearing algorithmCleaned heap memory , There will be a lot of memory fragmentation .
explain
Select which allocation method is determined by Java Whether the pile is regular or not , and Java Whether the heap is regular or not depends on whether the garbage collector is equipped with compression and sorting function .
Dealing with concurrency security issues
use
CAS Failure to retry、Area lockingEnsure the atomicity of updatesEach thread is pre allocated a block TLAB
But the qualification space is very small, you can pass -XX:+/-UseTLAB Parameters to set
Initialize allocated space
All properties set default values , Ensure that the object instance field can be used directly without assignment ( Zero initialization )
Set the object header of the object
Will be the object of
Category ( That is, the metadata information of the class )、Object's HashCodeandObject's GC Information、Lock information, etcThe data is stored in the object header of the object . How this process is set depends on JVM Realization .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 .( Explicit initialization of properties 、 Initialization in the code block 、 Initialization in constructor )
So in general ( By whether the bytecode is followed by invokespecial Determined by the order ),new The instruction is followed by the execution method , Initialize the object according to the programmer's wishes , Such a really usable object is completely created .From the perspective of bytecode init Method
/** * Test object instantiation process * ① Loading class meta information - ② Allocate memory for objects - ③ Dealing with concurrency - ④ Property ( Zero initialization ) * - ⑤ Set the information of the object header - ⑥ Explicit initialization of properties 、 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 */ public class Customer{ int id = 1001; String name; Account acct; { name = " Anonymous clients "; } public Customer(){ acct = new Account(); } } class Account{ }
Object instantiation process
① Loading class meta information - ② Allocate memory for objects - ③ Dealing with concurrency - ④ Property ( Zero initialization )
⑤ Set the information of the object header - ⑥ Explicit initialization of properties 、 Initialization in the code block 、 Initialization in constructor
Only ⑥ That's what we can see in bytecode ,① To ⑤ They are all operations during compilation or class loading
2. Memory layout of objects

2.1 Object head (Header)
2.1.1 Runtime metadata (Mark word)
- Hash value (HashCode)
- GC Generational age
- Lock status flag
- Thread holds lock
- To the thread ID
- Bias timestamp
2.1.2 Type a pointer
Point to class metadata InstanceKlass, Determine the type the object belongs to . It actually points to the class meta information stored in the method area
If it's an array , You also need to record the length of the array
2.2 The instance data (Instance Data)
2.2.1 explain
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 )
2.2.2 The rules
- 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
2.3 Alignment filling (Padding)
It's not necessary , It doesn't mean anything , It's just a place holder
2.4 Summary : Icon

2.5 Object instantiation stack , Pile up , Relationship of method area
Sample code
public class Customer{ int id = 1001; String name; Account acct; { name = " Anonymous clients "; } public Customer(){ acct = new Account(); } } class Account{ }

- The direct reference in the local variable table in the stack points to the object instance in the heap space
- Object instances contain object headers ( Runtime metadata , Type a pointer ), The instance data , Alignment filling
- The type pointer of the object header points to the class meta information of the method area Customer Instantiation
- But there is another object reference in the instance data, and the above three steps will be repeated to instantiate this object , Until all objects are instantiated
3. Object access location

3.1 Icon

3.2 There are two ways to access objects
3.2.1 Handle access

advantage :reference Store the stable handle address in , Objects are moved ( It is common to move objects during garbage collection ) Only the instance data pointer in the handle will be changed ,reference It doesn't need to be modified .
shortcoming : You need heap space to allocate space separately as a handle pool , meanwhile reference The step size to the object instance data is also increased
3.2.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 : There is no need to allocate heap space separately as a handle pool , meanwhile reference Point directly to an instance in the heap
shortcoming : The object needs to be modified when moving reference
边栏推荐
- 事件过滤器
- JVM上篇:内存与垃圾回收篇五--运行时数据区-虚拟机栈
- JVM上篇:内存与垃圾回收篇三--运行时数据区-概述及线程
- JVM上篇:内存与垃圾回收篇七--运行时数据区-堆
- Laozi cloud and Fuxin Kunpeng achieved a major breakthrough in 3D ofd 3D format documents for the first time
- Transaction database and its four characteristics, principle, isolation level, dirty read, unreal read, non repeatable read?
- Acceptance and neglect of events
- Why is count (*) slow
- MQ message queue is used to design the high concurrency of the order placing process, the generation scenarios and solutions of message squeeze, message loss and message repetition
- Flexible array and common problems
猜你喜欢

Li Kou achieved the second largest result

How does PS import LUT presets? Photoshop import LUT color preset tutorial

文件对话框

树莓派rtmp推流本地摄像头图像

Another skill is to earn 30000 yuan a month+

Typescript details

35.滚动 scroll

JVM上篇:内存与垃圾回收篇十一--执行引擎

Laozi cloud and Fuxin Kunpeng achieved a major breakthrough in 3D ofd 3D format documents for the first time

JVM Part 1: memory and garbage collection part 6 -- runtime data area local method & local method stack
随机推荐
Be diligent in talking about what sidelines you can do now
文件对话框
使用Druid连接池创建DataSource(数据源)
辗转相除法
Static and final keyword learning demo exercise
Deep Qt5 signal slot new syntax
Select user stories | the false positive rate of hole state in jushuitan is almost 0. How to do this?
对话框简介
feign调用丢失请求头问题解决及原理分析
[Niuke discussion area] Chapter 7: building safe and efficient enterprise services
Hiding skills of Photoshop clipping tool
Solution to Dlib installation failure
Sunset red warm tone tinting filter LUTS preset sunset LUTS 1
事件的接受与忽略
Transaction database and its four characteristics, principle, isolation level, dirty read, unreal read, non repeatable read?
Counting Nodes in a Binary Search Tree
Why is count (*) slow
How to store the startprocessinstancebykey method in acticiti in the variable table
求组合数(最强优化)
Sub database and sub table