当前位置:网站首页>[JVM] class loading related interview questions - class loading process and parental delegation model
[JVM] class loading related interview questions - class loading process and parental delegation model
2022-06-30 17:02:00 【Classmate pan】
List of articles
introduction :
Class loading , It is actually an important core function of designing a runtime environment , Here are the common interview questions
What does class loading do ? Is to put .class file , Load into memory , Build as class object .
Class loading process
For a class , Its life cycle is like this :
among front 5 The steps are in a fixed order And it's also The process of class loading , In the middle 3 We all belong to the connection , Therefore, class loading is divided into the following steps :
- load
- Connect
- verification
- Get ready
- analysis
- initialization
in other words , The whole class loading process , There are three big steps !!!Loading( load )、Linking( Connect )、and Initialization( initialization )
Small tip: It is suggested that you try to answer in English during the interview , Otherwise, you will say loading in the first step , In case the interviewer asks you about class loading , Your first step is to load , Is it all loaded , It's easy to have ambiguity , It may be more rigorous to answer in English
- Loading link
“ load ”(Loading) The stage is the whole “ Class loading ”(Class Loading) A stage in the process , It and class loading Class
Loading Is different , One is loading Loading The other is class loading Class Loading, So don't confuse the two
In the load Loading Stage ,Java There are three things virtual machines need to do :
1) Get the binary byte stream that defines this class by using the fully qualified name of a class .
2) Convert the static storage structure represented by the byte stream into the runtime data structure of the method area .
3) Generate a representation of this class in memory java.lang.Class object , As the access to all kinds of data of this class in method area .
In summary, it is First find the corresponding .class file , Then open and read .class file , At the same time, a class object is preliminarily generated
Loading A key link in , .class What exactly is inside the file 
According to the format in the above figure , Read and parse the information , Initially fill in the class object
- Linking A connection is usually a connection between multiple entities
1) verification (Verification)
The main task is to verify whether the read content exactly matches the format specified in the specification , If you find that the data format read here does not conform to the specification , Class loading fails , And throw an exception
2) Get ready (Preparation)
The preparation phase is formal For variables defined in a class ( That is, static variables , By static Decorated variable ) Allocate memory and set class variable initializers ( by 0) The stage of
3) analysis (Resolution)
The parsing phase is Java The process of virtual machine replacing symbolic reference in constant pool with direct reference , That is, the process of initializing constants .
Because in .class In file , Constants are centrally placed , Each constant has a number ,.class The initial information in the structure of the document is only the number , So you need to find the corresponding content according to the number , Fill in class objects . - Initialization initialization
Actually initialize the class object , Especially for static members
Classic interview questions
When is the chance to trigger the loading of a class ( The code for )?
As long as this class is used , You need to load this class first ( Instantiation , Calling method , Call static methods , Be inherited … Are used )
class A{
public A(){
System.out.println("A Construction method of ");
}
{
System.out.println("A The construction code block of ");
}
static {
System.out.println("A Static code block ");
}
}
class B extends A{
public B(){
System.out.println("B Construction method of ");
}
{
System.out.println("B The construction code block of ");
}
static {
System.out.println("B Static code block ");
}
}
public class Test extends B{
public static void main(String[] args) {
new Test();
new Test();
}
}
Our procedure is from main Method start execution ,main Here is Test Methods , Therefore, execute main, You need to load Test, and Test Inherited from B, To load Test, You have to load B,B Inherited from A, To load B, You have to load A.
The loading process is as follows :
give the result as follows :
Remember these big principles :
- The class loading phase executes static code blocks , To create an instance , You must load the class first ;
- Static code blocks are only executed once during the class load phase
- Construction methods and code blocks , Each instantiation will execute , The construction code block precedes the construction method
- The parent class is executed before , Subclasses are executed after
- Our procedure is from main Start execution ,main Here is Test Methods , Therefore, execute main You need to load Test
Java Class initialization order : Parent static variables –> Parent static code block –> Subclass static variables –> Subclass static code block –> The parent class is not a static variable –> Parent class non static code block –> Parent constructor —> Subclass nonstatic variables –> Subclass non static code block —> Subclass constructor
Class loader
JVM Special objects are provided in , It's called a class loader , Responsible for class loading , Of course, the class loader is also responsible for the process of finding files . because .class There are many places where files can be placed , Some should be put in JDK Directory , Some are put in the project directory , Others are in other specific locations , therefore JVM It provides multiple class loaders , Each class loader is responsible for a partition .
The default class loaders are mainly the following :
- BootstrapClassLoader
Responsible for loading classes in the standard library (String ,ArrayList ,Random ,Scanner…) - ExternsionClassl oader
Responsible for loading JDK Extended classes ( It is rarely used nowadays ) - ApplicationClassLoader
Be responsible for loading the classes in the current project directory
Programs can also customize class loaders , To load classes in other directories , such as :Tomcat The class loader is customized , Used to specifically load webapps Inside .class
About “ Parent delegation model ”
This thing is a part of class loading , be in Loading Stage . The parental delegation model describes JVM Class loader in , How to give a fully qualified name to a class (java.lang.String) find .class Documentation process . Describes the process of finding directories , That is, how the above class loaders work together .
The above set of search rules , It's called “ Parent delegation model ”, See this , Some children's shoes have doubts , The parental delegation model , How can this light father , Mother is actually parent It means father , It also means mother , Some materials are directly translated into " Parents ", It refers to one of the parents individual .
Why? JVM Design like this ?
The reason is : Once the program ape writes its own class , And classes in the standard library , The fully qualified class name is repeated , It can also smoothly load classes into the standard library
Such as :java.lang.String Such a class , If the program tries to load this class , What is loaded is the class in the standard library , If you want to load into our custom class , That is through ApplicationClassLoader To load the , then ApplicationClassLoader Will report to ExternsionClassloader, Then it reports to BootstrapClassLoader, then BootstrapClassLoader It is loaded directly , Therefore, it is impossible to ApplicationClassLoader To load your own classes .
If it is a custom class loader , Whether to follow the parental delegation model
Can be observed , Or not , See the demand .
such as : image tomcat load webapp Class in , Did not comply ( Because it doesn't make sense to abide by it )

边栏推荐
- 搬运两个负载均衡的笔记,日后省的找
- 中航无人机科创板上市:市值385亿 拳头产品是翼龙无人机
- 声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏
- Half year inventory of new consumption in 2022: the industry is cold, but these nine tracks still attract gold
- List announced - outstanding intellectual property service team in China in 2021
- [demo] write file circularly
- 微信表情符号写入判决书,你发的OK、炸弹都可能成为“呈堂证供”
- 异常类_日志框架
- Drug management system plus database, overnight, plus report
- go-micro教程 — 第一章 快速入门
猜你喜欢

利用PIL进行不失真的resize

巩固入门-C#基础变量和常量

idea必用插件

7 月 2 日邀你来TD Hero 线上发布会

Good partner for cloud skill improvement, senior brother cloud of Amazon officially opened today

TCP Socket与TCP 连接
![[wechat applet] the hosting environment of the applet](/img/ee/0f1dee4a26eb62c2268484c1b59edf.png)
[wechat applet] the hosting environment of the applet
![[wechat applet] basic use of common components (view/scroll-view/wiper, text/rich-text, button/image)](/img/3b/05dbf03024088c5f94363f157a1701.png)
[wechat applet] basic use of common components (view/scroll-view/wiper, text/rich-text, button/image)

Niuke: how many different binary search trees are there

Tutoriel etcd - chapitre 8 API compacte, Watch et lease pour etcd
随机推荐
牛客网:乘积为正数的最长连续子数组
赛芯电子冲刺科创板:拟募资6.2亿 实控人谭健为美国籍
Undistorted resize using pil
Rongsheng biology rushes to the scientific innovation board: it plans to raise 1.25 billion yuan, with an annual revenue of 260million yuan
register_ Chrdev and CDEV_ init cdev_ Add usage differences
IO stream_ recursion
The 25th anniversary of Hong Kong's return to China the Hong Kong Palace Museum officially opened as a new cultural landmark
BC1.2 PD协议
Eight basic sorting (detailed explanation)
Etcd教程 — 第八章 Etcd之Compact、Watch和Lease API
AVIC UAV technology innovation board is listed: the fist product with a market value of 38.5 billion is pterodactyl UAV
Etcd教程 — 第八章 Etcd之Compact、Watch和Lease API
坚果云-在新电脑上同步移动硬盘的文件
居家办公浅谈远程协助快速提效心得 | 社区征文
观测云与 TDengine 达成深度合作,优化企业上云体验
Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
Observation cloud reached in-depth cooperation with tdengine to optimize enterprise cloud experience
Several cross end development artifacts
9: Chapter 3: e-commerce engineering analysis: 4: [general module]; (to be written...)
IO流_递归