当前位置:网站首页>Class initialization mechanism of JVM
Class initialization mechanism of JVM
2022-07-26 16:12:00 【Flying watermelon】
When you are in Java In the program new Object time , Have you considered JVM How to put static bytecode (byte code) To run time objects , The question seems simple , But clear students believe that there will not be too many , This article first introduces JVM Class initialization mechanism , And then give several error prone examples to analyze , Help you understand this knowledge better .
Loading, Linking, and Initialization
JVM Converting bytecode into runtime objects is divided into three stages , Namely :loading 、Linking、initialization.
These three processes are introduced below :
Loading
Loading The main task of the process is to ClassLoader complete . The process includes three things :
- According to the full name of the class , Generate a binary bytecode to represent the class
- Parse the binary bytecode into the data structure corresponding to the method area
- Finally, we generate a
ClassObject to represent the class
JVM In addition to the top Boostrap ClassLoader Yes, it is C/C++ Out of implementation , The other class loaders are made up of Java Realization , We can use getClassLoader Method to get the class loader of the current class :
public class ClassLoaderDemo {
public static void main(String[] args) {
System.out.println(ClassLoaderDemo.class.getClassLoader());
}
}
# [email protected]
# AppClassLoader It's the one in the picture above System Class Loader Besides , We're starting java Pass in -verbose:class To see which classes are loaded .
java -verbose:class ClassLoaderDemo
[Opened /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Object from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.io.Serializable from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
....
....
[Loaded java.security.BasicPermissionCollection from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded ClassLoaderDemo from file:/Users/liujiacai/codes/IdeaProjects/mysql-test/target/classes/]
[Loaded sun.launcher.LauncherHelper$FXHelper from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Class$MethodArray from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Void from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[email protected]
[Loaded java.lang.Shutdown from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]
[Loaded java.lang.Shutdown$Lock from /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/jre/lib/rt.jar]Linking
Verification
Verification The main purpose is to ensure that the class conforms to Java Grammatical norms , Make sure it doesn't affect JVM Operation of . Including but not limited to the following :
- bytecode The integrity of (integrity)
- Check
finalClass is not inherited ,finalMethod is not overridden - Make sure there are no incompatible method signatures
Preparation
In a class that has been load And through verification after , Just enter preparation Stage . At this stage ,JVM It allocates memory space for the member variables of the class and gives the default initial value , It's important to note that no code is executed at this stage , But only based on Variable type Determine initial value . Without default initialization , The value of the allocated space is random , It's kind of c The problem of wild pointer in language .
Type Initial Value
int 0
long 0L
short (short) 0
char '\u0000'
byte (byte) 0
boolean false
reference null
float 0.0f
double 0.0d At this stage ,JVM It may also allocate memory for data structures that help improve program performance , A common one is called method table Data structure of , It contains methods that point to all classes ( It also includes methods that are inherited from the parent class ) The pointer to , In this way, when you call the parent class method again, you don't need to search .
Resolution
Resolution The main work of the stage is to confirm the class 、 Interface 、 Properties and methods in class run-time constant pool The location of , And quote these symbols (symbolic references) Replace with direct reference (direct references).
locating classes, interfaces, fields, and methods referenced symbolically from a type’s constant pool, and replacing those symbolic references with direct references.
This process is not necessary , It can also happen the first time a symbol reference is used .
Initialization
After the above load、link after , for the first time Active call The last step in a class is Initialization, This process will be initialized according to the code writing order , This phase is going to actually execute the code , Attention includes : Code block (static And static)、 Constructors 、 Variable explicit assignment . If a class has a parent , Will execute the parent class first initialization Stage , And then in the implementation of their own .
There are two key words in the above passage : for the first time And Active call . for the first time It means that the initialization process will only occur the first time , I don't need it anymore , It can be understood as each class There is and only once Opportunity to initialize . So what is Active call Well ? JVM The following six cases are specified as Active call , The rest are Passive call :
- An instance of a class is created (
newoperation 、 Reflection 、cloning, Deserialization ) - The calling class
staticMethod - Use or pair classes / Interface
staticProperty is assigned ( This does not includefinalAnd constant expressions determined at compile time ) - When calling API Some reflection methods in
- Subclass is initialized
- Be set to JVM The startup class at startup ( have
mainClass of method )
An example will be given later in this article to illustrate Active call Of Passive call difference .
At this stage , The order in which the code is executed follows two principles :
- Yes static Initialize first static, Then right and wrong static Of
- Explicitly initialize , Building block initialization , Finally, the constructor is initialized
Example
Property assignment in different periods
class Singleton {
private static Singleton mInstance = new Singleton();// Location 1
public static int counter1;
public static int counter2 = 0;
// private static Singleton mInstance = new Singleton();// Location 2
private Singleton() {
counter1++;
counter2++;
}
public static Singleton getInstantce() {
return mInstance;
}
}
public class InitDemo {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstantce();
System.out.println("counter1: " + singleton.counter1);
System.out.println("counter2: " + singleton.counter2);
}
} When mInstance In position 1 when , Print out
counter1: 1
counter2: 0 When mInstance In position 2 when , Print out
counter1: 1
counter2: 1Singleton The three attributes in Preparation Phases are assigned default values depending on the type , stay Initialization The stage will assign again based on the expression that shows the assignment ( Top down in order ). According to these two points , It's not hard to understand the above results .
Active call vs. Passive call
class NewParent {
static int hoursOfSleep = (int) (Math.random() * 3.0);
static {
System.out.println("NewParent was initialized.");
}
}
class NewbornBaby extends NewParent {
static int hoursOfCrying = 6 + (int) (Math.random() * 2.0);
static {
System.out.println("NewbornBaby was initialized.");
}
}
public class ActiveUsageDemo {
// Invoking main() is an active use of ActiveUsageDemo
public static void main(String[] args) {
// Using hoursOfSleep is an active use of NewParent,
// but a passive use of NewbornBaby
System.out.println(NewbornBaby.hoursOfSleep);
}
static {
System.out.println("ActiveUsageDemo was initialized.");
}
}The program above finally outputs :
ActiveUsageDemo was initialized.
NewParent was initialized.
1 The reason there is no output NewbornBaby was initialized. It's because I didn't take the initiative to call NewbornBaby, If you change the printed content to NewbornBaby.hoursOfCrying So this is the active call NewbornBaby 了 , The corresponding statement will also be printed out .
The first active call will initialize
public class Alibaba {
public static int k = 0;
public static Alibaba t1 = new Alibaba("t1");
public static Alibaba t2 = new Alibaba("t2");
public static int i = print("i");
public static int n = 99;
private int a = 0;
public int j = print("j");
{
print(" Tectonic block ");
}
static {
print(" A static block ");
}
public Alibaba(String str) {
System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
++i;
++n;
}
public static int print(String str) {
System.out.println((++k) + ":" + str + " i=" + i + " n=" + n);
++n;
return ++i;
}
public static void main(String args[]) {
Alibaba t = new Alibaba("init");
}
}The above example is Alibaba in 14 Additional questions of school enrollment in , I saw this question at the time , I feel that I have no chance with ALI . Embarrassed
1:j i=0 n=0
2: Tectonic block i=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5: Tectonic block i=4 n=4
6:t2 i=5 n=5
7:i i=6 n=6
8: A static block i=7 n=99
9:j i=8 n=100
10: Tectonic block i=9 n=101
11:init i=10 n=102Above is the output of the program , Next, I'll make a line by line analysis .
because Alibaba yes JVM The start of class , It belongs to active call , So it's going to be like this loading、linking、initialization Three processes .
after loading And linking After the stage , All properties have default values , And then into the final initialization Stage .
stay initialization Stage , First pair static Attribute assignment , And then in Africa static Of .k The first explicit assignment is 0 .
Next is t1 attribute , Because at this moment Alibaba This class is already in initialization Stage ,static Variables don't need to be initialized again , So ignore static Assignment of a property , Only right and wrong static The property of , All that has a beginning :
Then on t2 Assign a value , Process and t1 identical
Then came static Of i And n:
Up to now , be-all static The member variable of has been assigned , And here we are static Code block
thus , be-all static Partial assignment complete , Next, right and wrong static Of j
All properties are assigned , Finally, building blocks and constructors
Pass by here 9 Step ,Alibaba The initialization of this class is complete . One of the things that's more likely to go wrong is 3 Step , Think it will initialize again static Variables or code blocks . And it's not really necessary , Otherwise, there will be multiple initializations .
I hope you can think more about the results of this example , Deepen the understanding of these three processes .
summary
After the last three examples , I'm sure you're right JVM Have a deeper understanding of the class loading mechanism , If you still have questions , Welcome to pay attention to the discussion .
Reference resources
- Java Virtual Machine Specification Chapter 5
- Chapter 7 of Inside the Java Virtual Machine
- JVM Internals
- What kind of method is Constructor, static or non static?
- Understanding the Java ClassLoader
边栏推荐
- Summary of key knowledge of C language
- Robot hand eye calibration ax=xb (eye to hand and eye in hand) and plane nine point calibration
- Google Earth engine - merra-2 m2t1nxaer: aerosol daily data set from 1980 to 2022
- 大型仿人机器人整机构型研究与应用
- First knowledge of OpenGL (2) compilation shaders
- Google Earth engine - merra-2 m2t1nxlv: 1980 present global pressure, temperature, wind and other data sets
- [RCTF2015]EasySQL
- C语言重点知识总结
- 终于有人把红蓝对抗讲明白了
- Mapwithstate of spark streaming state flow
猜你喜欢
![[physical simulation] the principle and practice of the simplest shape matching](/img/1e/d91ed992bc648d90d0c68bfe541d7e.jpg)
[physical simulation] the principle and practice of the simplest shape matching

我们被一个 kong 的性能 bug 折腾了一个通宵

A comprehensive review of image enhancement technology in deep learning

【工具分享】自动生成文件目录结构工具mddir
![[RCTF2015]EasySQL](/img/68/328ee5cffc8b267b6b0f284eb8db2c.png)
[RCTF2015]EasySQL

2022年最新西藏建筑施工架子工(建筑特种作业)模拟考试试题及答案

Some cutting-edge research work sharing of SAP ABAP NetWeaver containerization
![[tool sharing] automatic generation of file directory structure tool mddir](/img/bc/1071c0dfb20d16f5fdde641092c1af.png)
[tool sharing] automatic generation of file directory structure tool mddir

Google Earth Engine——MERRA-2 M2T1NXAER:1980-2022年气溶胶逐日数据集

Botu PLC Sequential switch function block (SCL)
随机推荐
CAD进阶练习题(一)
想让照片中的云飘起来?视频编辑服务一键动效3步就能实现
Google Earth Engine——MERRA-2 M2T1NXSLV:1980-至今全球压力、温度、风等数据集
如何通过ETL调度工具 TASKCTL 使用作业插件类型调用 kettle作业?
2021年软件测试工具趋势
潘多拉 IOT 开发板学习(RT-Thread)—— 实验17 ESP8266 实验(学习笔记)
Google Earth Engine——MERRA-2 M2T1NXAER:1980-2022年气溶胶逐日数据集
Implementation of SAP ABAP daemon
朋友圈如何测试(思维导图)
换把人体工学椅,缓解久坐写代码的老腰吧~
SQL statement -- single line comment and multi line comment
Parker solenoid valve d1vw020dnypz5
2022年最新西藏建筑施工架子工(建筑特种作业)模拟考试试题及答案
Delta controller rmc200
spark-streaming状态流之mapWithState
js 对数组操作的 API 总结
First knowledge of OpenGL (2) compilation shaders
Implementation of personalized healthy diet recommendation system based on SSM
Is CICC Fortune Securities safe? How long does it take to open an account
Test cases should never be used casually, recording the thinking caused by the exception of a test case