当前位置:网站首页>[jvm learning] class loading subsystem
[jvm learning] class loading subsystem
2022-06-12 15:13:00 【Aiyouwei】
JVM– Class loading subsystem
Overview of class loading subsystem
- Class loading subsystem is responsible for loading from file system or network class file (class The file has a specific identifier at the beginning of the file )
- The class loading subsystem is only responsible for class Loading of files , As for whether the class can run, there is an execution engine (Execution Engine) decision
- The loaded class information is stored in a block of memory called the method area , In addition to class information , The method area will also contain information about the runtime constant pool , It may also include string literals and numeric constants ( This part of the constant information is Class Memory mapping for the constant pool part of the file )
- An overview of the class loading subsystem is shown below

The process of class loading

Linking process
load
- Get the binary byte stream of a class through its fully qualified name
- Convert the static storage structure represented by the byte stream into the runtime data structure of the method area
- Generate a representation of this class in memory java.lang.Class object , As various data access entries for this class in the method area
- Add : load .class How to file
- Load directly from the local system
- Get... Through the Internet , Typical scenario :web applet
- from zip Read in compressed package , Become the future jar、war The basis of format
- Runtime compute generation , The most commonly used is dynamic proxy technology
- Generated from other files , Typical scenario :JSP application
- Extract... From a proprietary database .class file , Relatively rare
- Get... From the encrypted file , Typical defense Class The protection of the file against decompilation
The three processes of linking
- verification (verify)
- The purpose is to ensure class The information contained in the byte stream of the file meets the requirements of the current virtual machine , Make sure the loaded class is correct , It will not harm the security of the virtual machine itself
- It mainly includes four kinds of verification : File format validation , Metadata validation , Bytecode verification , Symbol reference validation
- Get ready (Prepare)
- Allocate memory for a class variable and set the default initial value of the class variable , That's zero ( Class variables are static variables )
- It does not contain final Embellished static, because final It will be allocated at compile time , The preparation phase will explicitly initialize
- There is no initialization assigned to instance variables , Class variables are assigned in the method area , And instance variables are assigned to along with the object java In the pile
- analysis (Resolve)
- The process of converting a symbolic reference in a constant pool into a direct reference
- Parsing is often accompanied by JVM Execute after initialization
- Symbol reference is a set of symbols to describe the referenced target , A direct reference is a pointer directly to the target , Relative offset or an indirect handle to the target
- Parsing actions are mainly for classes or interfaces 、 Field 、 Class method 、 Interface method 、 Method type, etc , Corresponds to... In the constant pool CONSTANT_Class_info、CONSTANT_Fieldref_info、CONSTANT_Methodref_info etc.
- verification (verify)
initialization (Initialization)
- The initialization phase is the execution of class constructor methods clinit() The process of
- The method is javac The compiler automatically collects the assignment actions of all class variables in the class and the statements in the static code block
- The instructions in the constructor method are executed in the order that the statements appear in the source file
- clinit() Constructor different from class ( relation : The constructor is from the perspective of virtual machine init())
- If the class has a parent class ,JVM Will guarantee the subclass clinit() Before execution , Of the parent class clinit() Execution completed
public class ClinitTest1 { static class Father{ public static int A =1; static{ A = 2; } } static class Son extends Father{ public static int B= A; } public static void main(String[] args) { // load Father class , Second, load Son class , System.out.println(Son.B);// 2 } }
- The virtual machine must guarantee a class of clinit() Method is locked synchronously under multithreading , The following is an example
public class DeadThreadTest { public static void main(String[] args) { Runnable r = () -> { System.out.println(Thread.currentThread().getName()+" Start "); DeadThread dead = new DeadThread(); System.out.println(Thread.currentThread().getName()+" end "); }; Thread t1 = new Thread(r," Threads 1"); Thread t2 = new Thread(r," Threads 2"); t1.start(); t2.start(); } } class DeadThread{ static { if(true){ System.out.println(Thread.currentThread().getName()+" Initialize the current class "); while(true){ } } } }The output of the above code block is :
Threads 1 Start
Threads 2 Start
Threads 1 Initialize the current class
When the initialization DeadThread Class time , The cycle did not come out , So class clinit() Method not completed , The system is locked , The second thread cannot execute
Loading phase -- Class loader
- JVM Supports two types of loaders , These are the boot class recorders (Bootstrap ClassLoader) And user-defined loading classes (User-Defined ClassLoader)
- conceptually , Custom loader generally refers to a kind of loader customized by developers in the program , and java Virtual machine specification query There is no such definition , It's all derived from abstract classes ClassLoader Class loaders are divided into custom class loaders
- Regardless of the type of class loader , Our most common class loaders in our programs are always just three , As shown in the figure below :

- Start class loader ( Boot class loader ,Bootstrap Class Loader)
- This class uses C/C++ Realization , Nested in JVM Inside
- It's used to load Java The core of the library , For providing JVM I need
- Not inherited from java.lang.ClassLoader, No parent class loader
- Load extension classes and application load classes , And specify their parent loader
- For safety reasons .BootStrap The boot class loader only loads packages named java,javax,sun Initial class
- The loader of the virtual machine – Extend the classloader (Extension Class Loader)
- Java Language writing , from sun.misc.Launcher$ExtClassLoader Realization
- Derive from ClassLoader class
- The parent loader is the boot loader
- from java.ext.dirs Load the class library in the directory specified by the system property , Or from JDK Of the installation directory jre/lib/ext subdirectories ( Extended Directory ) Download the class library , If the user created JAR Put it in this directory , It will also be automatically loaded by the extension class loader
String exDirs = System.clearProperty("java.ext.dirs"); for (String path : exDirs.split(";")){ System.out.println(path); } /** * ********** Extend the classloader ********** * D:\Program Files\Java\jdk1.8.0_144\jre\lib\ext * C:\WINDOWS\Sun\Java\lib\ext */ - The loader of the virtual machine — Application class loader ( system class loader ,App Class Loader)
- Java Language writing , from [email protected] Realization
- Derive from ClassLoader class
- The parent class loader is the extension class loader
- It's responsible for loading environment variables classpath Or system properties java.class.path Specify the class library under the path
- This class loader is the default class loader selected , Generally speaking ,Java The application class is loaded by it
- adopt ClassLoader.getSystemClassLoader(); You can get the class loader
System.out.println("********** Start class loader **********"); // obtain bootstrapclassloader Able to load api The path of URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs(); for (URL element : urls){ System.out.println(element.toExternalForm()); } /** * ********** Start class loader ********** * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/resources.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/rt.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/sunrsasign.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jsse.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jce.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/charsets.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/lib/jfr.jar * file:/D:/Program%20Files/Java/jdk1.8.0_144/jre/classes */ - User defined class loader
- Why custom class loaders
- Isolation loading class
- Modify how classes are loaded
- Extended load source
- Prevent source code leaks
- User defined simple steps
- Developers can inherit abstract classes java.lang.ClassLoader Kind of the way , Implement your own classloader
- JDK1.2 Before , When customizing class loaders , Always inherit ClassLoader Class and rewrite loadClass() Method , So as to implement the custom class loading class , stay JDK1.2 It is not recommended that users overwrite loadClass() Method , Instead, it is recommended that the custom class loading logic be written in findClass() In the method
- When writing custom class loaders , If there are no overly complex requirements , Can inherit directly URLClassLoader class , In this way, you can avoid writing by yourself findClass() Method and method for obtaining byte code stream , Make the writing of custom class recorder more concise
- Why custom class loaders
// Get system classloader
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);//[email protected]
// Get the top
ClassLoader extClassLoader = systemClassLoader.getParent(); //[email protected]
System.out.println(extClassLoader);
// Get the top , Could not get boot class loader
ClassLoader parent = extClassLoader.getParent();
System.out.println(parent); //null
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader(); // [email protected]
System.out.println(classLoader);
// String Class loads using the bootstrap class loader -- > java The core class loaders of are loaded by the boot class loader
ClassLoader classLoader1 = String.class.getClassLoader(); // null
System.out.println(classLoader1);
边栏推荐
- How to write year-end summary
- C main函数
- The difference and brief description of "file name" and < file name > import header file used in # include
- 函数递归示例
- Common assertions in JUnit testing
- SQL cross database injection
- Jetpack architecture component learning (3) -- activity results API usage
- C语言打开中文路径文件
- Error 1105: message:\“raft entry is too large
- Ali suggests that all POJO attributes use wrapper classes, but have you noticed these pits?
猜你喜欢
随机推荐
About layoffs in Internet companies
C scanf函数
Qiming cloud sharing | demonstrate the switch through an example of the matter protocol to control the light on and off through the matter protocol
三维重建系统 | L3双视角运动恢复结构(SFM双目SFM)
C 转义字符
Writing method of JUnit multithreading
Module yaml error: Unexpected key in data: static_ context [line 9 col 3]
Structure example
ADSL
PHPstudy建站提示hosts文件可能不存在或被阻止打开,同步hosts失败怎么解决
Differences between microservice architecture and SOA Architecture
解决log4j2漏洞遭到挖矿、僵尸进程病毒攻击
Rust tip - running the tensorrt model through FFI programming
Change according to the situation, the road to promotion in the second half of 2022
C main函数
频繁项集产生强关联规则的过程
分布式并发重复提交问题
tc菜单分割
安装PS软件时提示程序无法访问关键文件/目录,错误代码:41的解决方法
h3c GR5200路由器上如何设置公网ip可以访问









