当前位置:网站首页>[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);
边栏推荐
- Kinect2.0+ORBSLAM2_with_pointcloud_map
- How to add WWW to the domain name
- Swap numbers, XOR, operator correlation
- 粒子滤波学习记录
- Getting started with webdriver
- Differences between microservice architecture and SOA Architecture
- 频繁项集产生强关联规则的过程
- MH32F103ARPT6软硬件兼容替代STM32F103RCT6
- [LDA] LDA theme model notes - mainly Dirichlet
- Scala download and idea installation of scala plug-ins (nanny level tutorial is super detailed)
猜你喜欢

增加mysql的最大连接数

Kinect2.0+ORBSLAM2_with_pointcloud_map

Deepin20.6 rtx3080 installer le lecteur de carte graphique 510.60.02, cuda 11.6, pytorch1.11

Pointer related concepts

Getting started with webdriver

ROS beginners write the server that the little turtle rotates a certain angle at a certain speed

PTA:自测-2 素数对猜想 (20分)

Deepin20.6 rtx3080 installing graphics card drivers 510.60.02, cuda11.6, pytorch1.11
![[wp][beginner level] attack and defense world game](/img/07/1ea54d14ba3caca25a68786d5be4a6.png)
[wp][beginner level] attack and defense world game

Multi thread knowledge induction
随机推荐
C 字符串
TF learning notes in ROS
Rust小技巧 - 通过FFI编程运行tensorrt模型
[LDA] basic knowledge notes - mainly AE and VAE
Pta: self test -2 prime pair conjecture (20 points)
Ngork implements intranet penetration -- free
Learning records of new keywords, references & pointers
JUnit test suite method sorting (method 2 is not easy to use)
Jetpack architecture component learning (3) -- activity results API usage
Assertion of selenium webdriver
ADSL
Autofac Beginner (1)
How to write year-end summary
Array related content
Increase the maximum number of MySQL connections
如何写年终总结
同花顺手机炒股开户安全吗
三维重建系统 | L3增量运动恢复结构(增量SFM)
NETCORE combined with cap event bus to realize distributed transaction - message (2)
#include使用“文件名“和<文件名>引入头文件的区别及简述