当前位置:网站首页>Creation process and memory layout of objects at JVM level
Creation process and memory layout of objects at JVM level
2022-06-27 08:17:00 【Little moon 6】
Java Species 5 Ways to create new objects
- Call the keyword new
This is also the most common way we start :
person p1 = new person("zs", 20, " male ");
- Use The reflex mechanism
There are two ways of reflecting mechanism , One is to use Class Class newInstance Method .
Call parameterless constructor .
person p2;
try {
p2=(person)Class.forName("ioText/tex2").newInstance();
// Or maybe
p2=person.getClass().newInstance();
}catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Another method is to call Constructor Class newInstance Method .java.lang.reflect.Constructor There's one in the class newInstance Method creates an object . We can call parameterized and private constructors through this method .
try {
Constructor<person> c=person.class.getConstructor();
person p3=c.newInstance();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
- call Clone() Method
Call again Clone Before the method , It should be noted that we must first implement Cloneable Interface , And define clone() Method .
person p = new person("zs", 20, " male ");
person p1= (person)p.clone();
- Deserialization method
When we serialize or deserialize an object ,jvm It will create a separate object for us . When we deserialize ,jvm Creating an object does not call the constructor . Before using deserialization , We need to look like Clone() The method is the same , Realization Serializable Interface .
try {
ObjectInputStream in =
new ObjectInputStream(new FileInputStream("D:/java2/ioText/text2.txt"));
person p = (person) in.readObject();
System.out.println(p);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
We compare the five creation methods , You'll find ways 1,2,3 Create an object with a constructor , Method 4,5 The constructor is not called .
| How it was created | Whether to call the constructor |
|---|---|
| Use new keyword | The constructor is called |
| Use Constructor Class newInstance Method | The constructor is called |
| Use Class Class newInstance Method | The constructor is called |
| Use clone Method | The constructor is not called |
| Using deserialization | The constructor is not called |
The above is forwarded to This article

Six steps of object creation
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 In the constant pool of Locate a symbolic reference to a class , Also check whether the class represented by the symbol reference has been loaded 、 Analytic and initialization .( That is, to judge whether class meta information exists ). without , So in the parental delegation mode , Use when The front class loader starts with classLoader+ Package name + Class called Key Search for the corresponding .class file . If not File found , Then throw ClassNotFoundException abnormal , If you find , Then load the class , And generate the corresponding Class Class object
2. Allocate memory for objects
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 .
If memory is regular , Use pointer collisions
If memory is regular , So the virtual machine will use the pointer collision method (Bump The Pointer) To assign... To an object Memory . It means that all used memory is on one side , Free memory is on the other side , There is a pointer in the middle as the boundary Point indicator , To allocate memory is just to move the pointer to the idle side for a distance equal to the size of the object . Such as If the garbage collector chooses 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 .
If the memory is out of order , The virtual machine needs to maintain a list , Use free list allocation
If memory is not regular , Used and unused memory interlace with each other , Then the virtual machine will be idle List method to allocate memory for objects . The virtual machine maintains a list , Record which memory blocks are available on , Again When allocating, find a large enough space from the list to divide it into object instances , And update the list . This kind of score The matching method becomes “ Free list (Free List)”.
explain : Select which allocation method is determined by Java Whether the pile is regular or not , and Java Whether the heap is regular depends on the garbage collection used Whether the device has a compression function determines .
3. Dealing with concurrency security issues
When allocating memory space , Another problem is to ensure that new Thread security at object time : Creating objects is very Frequent operation , Virtual machines need to solve the concurrency problem . Virtual machine uses two ways to solve the problem of concurrency : CAS ( Compare And Swap) Failure to retry 、 Area locking : Ensure the atomicity of pointer update operation ;.TLAB The action of memory allocation is divided into different spaces according to threads , That is, each thread Java In the pile Pre allocate a small piece of memory , This is called the local thread allocation buffer ,(TLAB , Thread Local Allocation Buffer) Whether the virtual machine uses TLAB, Can pass -XX:+/-UseTLAB Parameters to set .
4. Initialize the space allocated to
End of memory allocation , The virtual machine initializes the allocated memory space to zero ( Object headers are not included ). This step is guaranteed Verify that the instance field of the object is in Java The code can be used directly without assigning initial value , Programs can access these The zero value corresponding to the data type of the field .
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 、 Lock information, etc Data 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 , transfer Using class construction methods , The first address of the object in the heap is assigned to the reference variable .
So in general ( By whether the bytecode is followed by invokespecial Determined by the order ),new Instructions are followed by This means the execution method , Initialize the object according to the programmer's wishes , Only in this way can one truly usable object be counted All created .
Memory layout of objects

public class Customer {
int id = 1001;
String name;
Account acct;
{
name = " Anonymous clients ";
}
public Customer(){
acct = new Account();
}
}
class Account{
}public class CustomerTest {
public static void main(String[] args) {
Customer cust = new Customer();
}
}

Access object location

The general idea is In stack frame reference Access the heap area and then access the method area through the metadata pointer :

There are two specific implementations :

1. Handle access :

2. Direct Pointers (hotspot use ) More advantages

边栏推荐
- 安装jenkins
- MySQL environment variable configuration tutorial
- Lvgl GUI guide porting code to stm32
- 二叉树结构以及堆结构基础
- 【12. 最大连续不重复子序列】
- JS to judge the odd and even function and find the function of circular area
- 盲测调查显示女码农比男码农更优秀
- 【c ++ primer 笔记】第3章 字符串、向量和数组
- 【论文阅读】Intrinsically semi-supervised methods
- 2022爱分析· IT运维厂商全景报告
猜你喜欢

lvgl使用demo及说明2

Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage

Associated GIS: all roads lead to ue5 City

win10-如何管理开机启动项?

MySQL索引详解

All tutor information on one page

L'enquête en aveugle a montré que les femmes étaient meilleures que les hommes.

Experience record of Luogu's topic brushing

Coggle 30 days of ML July competition learning

无论LCD和OLED显示技术有多好,都无法替代这个古老的显示数码管
随机推荐
oracle怎样将字符串转为多行
Rust async: SMOL source code analysis -executor
March into machine learning -- Preface
Install Jenkins
期货反向跟单靠谱吗?
JS to print prime numbers between 1-100 and calculate the total number of optimized versions
Closure problem
Implementation principle of similarity method in Oracle
Lvgl GUI guide porting code to stm32
[daily practice] realization of product card animation effect
C how to call line and rows when updating the database
[paper reading] internally semi supervised methods
Etcd tutorial - Chapter 5 etcd etcdctl usage
Windows下mysql-8下载、安装、配置教程
ServletConfig与ServletContext
Redis master-slave replication and sentinel mode
(resolved) the following raise notimplementederror occurs when Minet tests
How to view program running time (timer) in JS
[13. number and bit operation of 1 in binary]
SIG associé: toutes les routes mènent à ue5