当前位置:网站首页>Class loading mechanism
Class loading mechanism
2022-07-01 19:41:00 【Chenyu】
1、 brief introduction
Java One advantage of the cliche is cross platform , Write once and run everywhere . Its core is JVM. that JVM What is it ?
We write Java It's using Java Language , And computers ? At the bottom, it only knows 0 and 1, And the languages between different platforms are not interconnected , So we can understand the program , But for a computer, it's just a bunch of garbled code .C Although languages can cross platforms , But it's still troublesome , It needs to recompile the adaptation , therefore Java Simply add a transit station between the source code and the operating platform , Run by it Java Compiled bytecode , Then translate into corresponding computer language according to different platforms , This is it. JVM.
JVM It is a virtual computer , Connect between source code and computer , It can recognize .class Bytecode file , After running, translate the bytecode file into the language corresponding to different operating platforms for the computer to read . So as long as the virtual machine can be translated into different computer languages according to different operating platforms , You can run programs on different platforms .

Java The running mechanism of the code is : Program source code .java→jdk The compiler → Bytecode file .class→ virtual machine (JVM) translator → Computer language → Computer reading .
1、JDK(Java Development Kit): Developer kits , It's development java The key to the program , Contains JRE,Java Development + function .
2、JRE(Java Runtime Environment):java Runtime environment , contain JVM,Java function .
3、JVM(Java Virtual Machine):java virtual machine , yes java The core part of cross platform .
2、 Class loading mechanism
2.1、 Class loading process
When While the program is running Need to use some class when ( class 、 Interface 、 Enumeration, etc ), If not in memory , You need to load the class , adopt load 、 Connect 、 initialization Three steps to complete class loading .JVM Is to allow preloading before using classes , But if there is an error in the class , There will be no error protection during preloading , Only when the program needs to use classes will it report errors .
JVM Can't run directly Java Code , need JDK The compiler in puts .java The files are compiled into .class After the document ,JVM To load .
load : Will class .class Binary data in the file is read to JVM in , Store in method area (1.8 Forever 、1.8 Metaspace ), At the same time, generate a... Representing this class in the heap java.lang.Class object ,Class Object encapsulates the data structure of the class , And provide the interface to access the data in the method area ( Reflection ).
Generated when the first class is used class object , Follow up every time new The object generated by this class , That's it Class The object is generated by the template .
Connect : Merge the data in memory into the runtime environment of the virtual machine
verification : Ensure that the information contained in the loaded byte stream conforms to JVM The specification of .
File format validation : Verify whether the byte stream conforms to the specification
Metadata validation : Semantic analysis of bytecode information , Ensure that the description information conforms to the specification .
Bytecode verification : Determine whether the semantics of the program conforms to the specification
Symbol reference validation : Ensure normal parsingGet ready : Allocate memory for class variables (static Embellished ), And initialize it to the default value . But be final static Modifying class variables will directly assign correct values , Not the default ( because final static After the variable is assigned, it cannot be changed ).
analysis : Replace the symbolic reference in the constant pool with a direct reference .
Symbol reference : Use a set of symbols to represent the goal
Direct reference : Pointer directly to the target 、 Handle that can locate the target .
initialization :Java Virtual machine execution class initialization statement , Will assign the correct initial value . If the parent class is not initialized, the parent class will be initialized first
(Java After compiling into bytecode, there is no concept of construction method , Only class initialization methods and object initialization methods .
The class initialization method is the class variable assignment statement 、 Static code block .
The object initialization method is the member variable assignment statement 、 Common code block 、 Finally, the construction method , But if there is no object initialization ( No, new object ) Object initialization methods will not be executed .)Initialize the static members of the parent class and static Sentence block
Subclass static members and static Sentence block
Normal members and non members of the parent class static Sentence block
Parent constructor
Subclass ordinary members and non members static Sentence block
Subclass constructor
Initialization is triggered only when the class is actively used :
1、new
2、 Accessing static variables of a class 、 Assign values to class static variables
3、 Calling static methods of a class
4、 The reflex mechanism
5、 Initializes a subclass of a class , The parent class will also initialize
6、 Start class or Main Method's class is initialized first
2.2、 Class loader
The class loader is responsible for the .class File loading to JVM Medium , After loading, a corresponding java.lang.class object , And once a class is JVM After loading , It will not be loaded again ( The fully qualified name of the class + Class loaders form a unique identifier ).JVM Load on demand , As long as a class is needed , Will load this class .

JDK There are three built-in class loaders :
- BootsStrapClassLoader Start class loader :%JAVA_HOME%/lib Under the jar Bao He class file . Mainly JVM The class you need , yes Java Run the core class library .c++ Language implementation
- Extend the classloader ( originally ExtClassLoader, stay JDK 1.9 after , Renamed as PlatformClassLoader):%JAVA_HOME%/lib/ext Under the jar Bao He class file . Developers can directly obtain and use
- AppClassLoader Application class loader : load classPath Next class file , The code we wrote .

In addition to the loader provided by the system , You can also customize the loader . All user-defined class loaders should inherit ClassLoader class , Then rewrite findClass Method
// Customize a class loader
public class MyClassLoader extends ClassLoader {
// To specify a class Path to file
private String classPath;
public MyClassLoader(String classPath) {
this.classPath = classPath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// Full class name
String file = classPath + name + ".class";
System.out.println(file);
try (BufferedInputStream bis= new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream baos =new ByteArrayOutputStream(); ){
int len;
byte[] data=new byte[1024];
while ((len=bis.read(data))!=-1){
baos.write(data,0,len);
}
// Gets the byte array in memory
byte[] bytes = baos.toByteArray();
Class<?> clazz = defineClass(null, bytes, 0, bytes.length);
return clazz;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
// test
public static void main(String[] args) {
MyClassLoader myClassLoader = new MyClassLoader("D:/mydata/");
try {
Class<?> clazz = myClassLoader.loadClass("BubbleSort");
System.out.println(" Class loader is :"+clazz.getClassLoader().getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}

2.3、 Parent delegate mechanism
JVM Three loading mechanisms :
- Overall responsible for : When a class loader loads a class , Other classes that this class references or depends on are also loaded by this class .
- Parent delegation : If a loader has a parent loader , Then the loading task will be pushed off to the parent class to complete , Only when the parent class cannot complete loading , Subclasses will be loaded by themselves
- cache : Loaded class The file will go into the cache , When you need to load this class again , Will get in the cache , Only when the cache does not exist , To load ( Think about when we write code , Every time a class is modified , Is it necessary to restart before it takes effect ?? This is the mechanism )
Mechanism of parental appointment : If a classloader receives a load request , It will not load itself first , Instead, delegate the request to the parent class , If the parent class also has a parent loader , Then continue to entrust , Until you reach the top level of the boot class loader , The boot class loader can load , You're back Class, If the startup class loader cannot finish loading , Then the subclass will try to load itself , If the load fails , Will prompt ClassNotFoundException abnormal .
The priority of parental delegation can prevent classes from being loaded repeatedly ( Overall responsible for ), It can also prevent malicious tampering by the core class library ( Such as starting class loader loading jar The files in the package , Unless you directly modify this machine JDK, Otherwise, it will not load other malicious files with the same name ).
If the class is loaded , Class loading will choose to fetch from the cache , Instead of reloading .
//ClassLoader Class source code , View parental delegation
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
synchronized (getClassLoadingLock(name)) {
// First , Check if the class has been loaded , If loaded , There is no need to load
Class<?> c = findLoadedClass(name);
// If it's not loaded , It depends on whether there is a parent loader
if (c == null) {
long t0 = System.nanoTime();
try {
// There is a parent loader , Get the parent loader , Calling the loadClass Method ( recursive )
if (parent != null) {
c = parent.loadClass(name, false);
} else {
// // No parent is loaded , from BootstrapClassLoader load
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// If not found, throw ClassNotFoundException
// from the non-null parent class loader
}
// If you still don't find , The trigger findclass, Throw out classNotFoundException
if (c == null) {
long t1 = System.nanoTime();
c = findClass(name);
// This is the definition class loader ; Record data
PerfCounter.getParentDelegationTime().addTime(t1 - t0);
PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
2.4、 The life cycle of a class
Java The virtual machine is Java The program provides the running environment , Manage the life cycle of both classes and objects : From the beginning of class loading to the end of class unloading .
load → verification → Get ready → analysis → initialization → Use → uninstall .
Java Every time you run a program, you start a Java Virtual machine process , The process from start to finish is the life cycle , In the following cases, the virtual opportunity ends its life cycle :
End of program execution
Terminate due to an exception or error during execution
Yes System.exit() Method
An error in the operating system caused the virtual machine to terminate
边栏推荐
- OpenCV视频质量诊断----视频遮挡诊断
- Wechat applet navigator has a shadow after clicking. Remove the shadow effect of navigator
- AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
- Ffmpeg error code
- 通过js实现金字塔(星号金字塔,回文对称数字金字塔)
- 241. Different Ways to Add Parentheses
- AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
- Introduction and installation of crunch, and making password dictionary with crunch
- CMU AI PhD 第一年总结
- IPv4 address, subnet mask, gateway
猜你喜欢

Les canaux de culture intensive s'efforcent de développer Fu Xin et Wei Shi jiajie pour organiser une conférence de formation sur les nouveaux produits

uni-app微信小程序一键登录获取权限功能

Shell advanced

wireshark报文分析tcp,ftp

JS 之 常用内置类的使用

精耕渠道共谋发展 福昕携手伟仕佳杰开展新产品培训大会

JVM内存模型

Facebook聊单,SaleSmartly有妙招!

求各种极限的方法

通过js实现金字塔(星号金字塔,回文对称数字金字塔)
随机推荐
703. The k-th element in the data flow
After studying 11 kinds of real-time chat software, I found that they all have these functions
AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
JDBC中如何添加事务
Transaction isolation level gap lock deadlock
Opencv video quality diagnosis - VIDEO occlusion diagnosis
任务:拒绝服务DoS
Learning records of building thingsboard, an Internet of things platform
Analysis of GetMessage underlying mechanism
通过js实现金字塔(星号金字塔,回文对称数字金字塔)
Salesmartly has some tricks for Facebook chat!
Opencv video quality detection -- sharpness detection
Solidity - contract structure - error - ^0.8.4 NEW
产品模块化设计的前世今生
面试题 16.16. 部分排序-双指针法
uni-app商品分类
Summary of SQL query de duplication statistics methods
CMU AI PhD 第一年总结
博途V16 获取系统时间转换成字符串
241. Different Ways to Add Parentheses