当前位置:网站首页>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
边栏推荐
猜你喜欢

Li Kou achieved the second largest result

JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads

Why is count (*) slow

How idea creates a groovy project (explain in detail with pictures and texts)

The project connects with Alipay payment, and the intranet penetration realizes the monitoring of asynchronous callback notification of successful payment of Alipay

老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破

pyside2____1.安装和案列

Read write separation and master-slave synchronization

"Photoshop2021 tutorial" align and distribute to make dot patterns

"Photoshop2021 tutorial" adjust the picture to different aspect ratio
随机推荐
Dialog data transfer
How idea creates a groovy project (explain in detail with pictures and texts)
34. Analyze flexible.js
Complete Binary Tree
Read write separation and master-slave synchronization
DBUtils
Deep Qt5 signal slot new syntax
B1025 反转链表*******
Counting Nodes in a Binary Search Tree
Row, table, page, share, exclusive, pessimistic, optimistic, deadlock
idea远程调试debug
How to copy Photoshop layers to other documents
Detailed explanation of pointer constant and constant pointer
Complete Binary Tree
树莓派rtmp推流本地摄像头图像
Introduction to MySQL optimization
File processing (IO)
Use of collection framework
"Photoshop2021 tutorial" align and distribute to make dot patterns
Invert a Binary Tree