当前位置:网站首页>In depth study of JVM bottom layer (V): class loading mechanism
In depth study of JVM bottom layer (V): class loading mechanism
2022-07-02 06:49:00 【I think starfish_ ninety-eight】
List of articles
Class loading mechanism
Concept
The virtual machine takes the data describing the class from Class File loaded into memory , And verify the data 、 Replace resolution and initialization , Finally, it can be directly used by virtual machine Java type
Class loading time
Pictured : Load in 、 verification 、 Get ready 、 The order of initialization and uninstallation is determined . The parsing phase can start after initialization ( Runtime binding or dynamic binding or late binding ).
The following five cases must initialize the class ( And load 、 verification 、 Preparation naturally needs to be completed before ):
- encounter new、getstatic、putstatic or invokestatic this 4 Trigger initialization is not initialized when byte code instruction is set . for example : Use new Keyword instantiation object 、 Read a static field of a class ( By final modification 、 Except for static fields that have been put into the constant pool at compile time )、 Call a static method of a class
- Use java.lang.reflect When a package's method makes a reflection call to a class
- When initializing a class , If it is found that its parent class has not been initialized , First trigger the initialization of its parent class
- When the virtual machine starts , The user needs to specify a main class to load ( contain main() Method type ), Virtual opportunity initializes the main class first
- When using JDK 1.7 Dynamic language support for , If one java.lang.invoke.MethodHandle The final parsing result of the example REF_getStatic、REF_putStatic、REF_invokeStatic Method handle for , And the class corresponding to this method handle has not been initialized , It needs to trigger its initialization first
Class loading process
load
- Get the binary stream that defines the subclass through the fully qualified name of a class (ZIP package 、 The Internet 、 Operation generation 、JSP Generate 、 Database read )
- 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 a method to access all kinds of data in this class
verification
This is the first step of connection , Make sure Class The information contained in the byte stream of the file meets the requirements of the current virtual machine
- File format validation : The first stage is to Verify that the byte stream matches Class Specification of document format , And can be processed by the current version of virtual machine . Verification points mainly include : Whether to count by magic 0xCAFEBABE start ; Lord 、 Is the minor version number within the current virtual machine processing range ; Is there an unsupported constant type in the constant of the constant pool ;Class Whether each part of the file and the file itself has been deleted or attached with other information, etc .
- Metadata validation : The second stage is right The information described by bytecode is analyzed semantically , In order to ensure that the information described in it conforms to Java The requirements of language norms , Verification points for this phase include : Does this class have a parent class ; Whether the parent class of this class inherits the class that is not allowed to be inherited ; If this class is not an abstract class , Whether it implements all the methods required to be implemented in its parent class or interface ; Fields in class 、 Whether the method conflicts with the parent class and so on .
- Bytecode verification : The third stage is the most complicated stage in the whole verification process , The main purpose is to analyze the data flow and control flow , Make sure the program semantics are legal 、 Logical .
- Symbol reference validation : The last phase of verification occurs when the virtual machine converts the symbol reference to a direct reference , This transformation will take place in the third phase of the connection – Occurs during the parsing phase . Symbol reference validation can be seen as Beyond the class itself ( Various symbol references in the constant pool ) The image of matching is checked .
Get ready
This stage formally allocates memory for the class and sets the initial value of the class variable , Memory is allocated in the method ( contain static Decorated variables do not contain instance variables )
analysis
This stage is the process of virtual machine replacing symbol reference in constant pool with direct reference .
initialization
Start executing in class Java Code .
Class loader
The virtual machine design team loads the classes in the **「 Get the binary byte stream that describes a class by its fully qualified name 」 This action is put in Java Virtual machine external to achieve , So that the application itself can decide how to get the required classes . The code module that implements this action is called 「 Class loader 」**.
Class loader Responsible for loading types in the program ( Classes and interfaces ), And give a unique name to identify .
Class and class loader
For any class , It needs to be established by the class loader that loads it and the class itself Java The uniqueness of virtual machines , Each class loader has a separate class namespace . in other words : Compare two classes whether or not 「 equal 」, It only makes sense if the two classes are loaded by the same class loader , otherwise , Even if the two classes come from the same Class file , Loaded by the same virtual machine , As long as the classloaders that load them are different , Then these two classes must not be equal .
Parent delegation model
from Java From a developer's point of view , Class loaders can be divided into :
- Start class loader (Bootstrap ClassLoader): This class loader is responsible for storing the <JAVA_HOME>\lib The class library in the directory is loaded into the virtual machine memory . The boot class loader cannot be Java The program directly refers to , When you write a custom class loader , If you need to delegate the load request to the boot class loader , Use Zener null Instead of just ;
- Extend the classloader (Extension ClassLoader): This class loader consists of sun.misc.Launcher$ExtClassLoader Realization , It's responsible for loading <JAVA_HOME>\lib\ext Directory , Or be java.ext.dirs All class libraries in the path specified by the system variable , Developers can use the extension class loader directly ;
- Application class loader (Application ClassLoader): This class loader consists of sun.misc.Launcher$App-ClassLoader Realization .getSystemClassLoader() Method returns the class loader , Therefore, it is also called system class loader . It is responsible for loading the user classpath (ClassPath) Class library specified on . Developers can use this classloader directly , If there is no custom classloader in the application , In general, this is the default classloader in the program .
Our applications are all made up of 3 The type loaders cooperate with each other to load , If necessary, you can also define your own class loader . Their relationship is shown in the figure below :
Class loader relationship
From the top down , Step by step
- Bootstrap Classloader Is in Java Initialized after the virtual machine starts .
- Bootstrap Classloader Responsible for loading ExtClassLoader, And will ExtClassLoader The parent loader of is set to Bootstrap Classloader.
- Bootstrap Classloader Finished loading ExtClassLoader after , Will be loaded AppClassLoader, And will AppClassLoader The parent loader of is specified as ExtClassLoader.
The function of classloader
Class loader features
- Hierarchical structure :Java The class loaders in are organized into a parent-child hierarchy .Bootstrap Class loaders are the father of all loaders .
- The proxy pattern : Based on hierarchy , Class can proxy between loaders . When the loader loads a class , First, it checks whether it is loaded in the parent loader . If the upper loader has already loaded this class , This class will be used directly . conversely , The class loader requests the class to be loaded
- Visibility limits : A child loader can find classes in the parent loader , But a parent loader cannot find classes in child loaders .
- Uninstall is not allowed : Class loader can load a class, but it can't unload it , However, you can delete the current class loader , Then create a new class loader to load .
Break the parental delegation model
To break the parental appointment mechanism, we should not only inherit ClassLoader class , And rewrite loadClass and findClass Method .
边栏推荐
- selenium备忘录:selenium\webdriver\remote\remote_connection.py:374: ResourceWarning: unclosed<xxxx>解决办法
- Automation - when Jenkins pipline executes the nodejs command, it prompts node: command not found
- Self study table Au
- Overload global and member new/delete
- Latex compilation error I found no \bibstyle &\bibdata &\citation command
- Asynchronous data copy in CUDA
- Kali latest update Guide
- ModuleNotFoundError: No module named ‘jieba. analyse‘; ‘ jieba‘ is not a package
- Latex error: the font size command \normalsize is not defined problem solved
- js中map和forEach的用法
猜你喜欢
随机推荐
Render minecraft scenes into real scenes using NVIDIA GPU
ZZQ的博客目录--更新于20210601
Redis -- cache breakdown, penetration, avalanche
Record RDS troubleshooting once -- RDS capacity increases dramatically
pytest(2) mark功能
记录一次RDS故障排除--RDS容量徒增
ModuleNotFoundError: No module named ‘jieba.analyse‘; ‘jieba‘ is not a package
Thread hierarchy in CUDA
(the 100th blog) written at the end of the second year of doctor's degree -20200818
js中map和forEach的用法
PIP install
Distributed transactions: the final consistency scheme of reliable messages
The intern left a big hole when he ran away and made two online problems, which made me miserable
js中对于返回Promise对象的语句如何try catch
selenium备忘录:selenium\webdriver\remote\remote_connection.py:374: ResourceWarning: unclosed<xxxx>解决办法
NodeJs - Express 中间件修改 Header: TypeError [ERR_INVALID_CHAR]: Invalid character in header content
QQ email cannot receive the email sent by Jenkins using email extension after construction (timestamp or auth...)
ctf三计
Automation - when Jenkins pipline executes the nodejs command, it prompts node: command not found
(第一百篇BLOG)写于博士二年级结束-20200818