当前位置:网站首页>JVM class loading
JVM class loading
2022-07-03 13:59:00 【It's hard to choose a name】
List of articles
jvm brief introduction
JVM yes Java Virtual Machine(Java virtual machine ) Abbreviation ,JVM Is a specification for computing equipment , It's an imaginary computer , It is realized by simulating various computer functions on a real computer . JVM Information related to specific operating system platform is blocked , send Java The program only needs to be generated in Java Target code running on virtual machine ( Bytecode ), It can run unmodified on multiple platforms .JVM When executing bytecode , In fact, the bytecode is ultimately interpreted as the execution of machine instructions on a specific platform .
compile
So I usually write it .java How files are entered jvm In the middle of ?
1、 First, through java Compiler will .java File compiled into jvm Recognable .class Bytecode file :javac xxx.java
Of course, bytecode files can also be decompiled into binary files , Re pass :javap xxx.class >xxx.txt take class File decompilation
java file :Test.java
package com.base.model;
public class Test {
private String name;
private static int age;
private static String sex="male";
public void run(){
System.out.println(this.name);
}
}
Translate it into class file :javac Test.java, Generate Test.class file
class The file is in binary format adopt javap take class File decompilation :javap Test.class >txt Output to the specified file
Or by adding parameters -v -p Translate it into jvm Command file
2、 Class loading will class File loaded into jvm in
Class loading
class file -----> Input stream -----> Load in jvm( Class loader ) technological process
1、 Virtual machine put Class File loaded into memory
3、 And verify the data , Transform resolution and initialization
3、 Form a virtual machine that can be used directly Java type , namely java.lang.Class
load
1、 Load directly from the local
2、 Download... Over the Internet .class file
scene :Web Applet, That is, our applet application
3、 from zip,jar Wait for the archive to load .class file
scene : Later evolved into jar、war Format
4、 take Java The source file is dynamically compiled as .class file , It's calculated at run time
scene : Dynamic proxy technique
5、 Get... From the encrypted file
scene : Typical defense Class The protection of the file against decompilation
1、 Get the binary byte stream that defines a class by its fully qualified name **( It can be seen from the above that , We don't have to start with bytecode files
gain , There are many other ways )
reflection : So do we need a tool at this time , Seeker , To find and get our binary byte stream . And ours
java There happens to be such a code module in . You can get the binary byte stream of this class through the full name of the class , And will
This action is put into java Virtual machine external to achieve , So that the application can decide how to get the required classes , Realize this action
The code module of becomes “ Class loader ”.
2、 Convert the static storage structure represented by the byte stream into the runtime data structure of the method area
3、 stay Java Generate a java.lang.Class object , As an access to the data in the method area
After our loading phase is complete , This time in our memory , Our runtime data area, method area and heap already have data Method area : Class information , Static variables , Constant
Pile up : Represents the of the loaded class java.lang.Class object
link
1、 verification : File format validation 、 Metadata validation 、 Bytecode verification 、 Symbol reference validation
2、 Get ready
Allocate memory for static variables of a class , And initialize it to the default value ()
use final Embellished static, because final It will be allocated at compile time
This is not an instance variable ( That is, No static) Allocation initialization , Class variables are assigned in the method area , And instance variables
It will be assigned to... Along with the object Java In the pile
Normal print out 0, Because static variables i There will be default values in the preparation phase 0
public class Demo1 {
private static int i;
public static void main(String[] args) {
// Normal print out 0, Because static variables i There will be default values in the preparation phase 0
System.out.println(i);
}
}
Compilation fails , Because local variables cannot be used without assignment
public class Demo2 {
public static void main(String[] args) {
// Compilation fails , Because local variables cannot be used without assignment
int i;
System.out.println(i);
}
}
3、 analysis : Convert symbolic references in a class to direct references
initialization
The initialization phase is the execution class constructor () Method process ; In the preparation stage , Class variable has been assigned the initial value required by the system once , And in the initialization phase , It initializes class variables and other resources according to the subjective plan made by the programmer through the program , Such as assignment
stay Java There are two ways to set the initial value of a class variable :
1、 Declaring a class variable is specifying the initial value
2、 Use static code blocks to specify initial values for class variables
According to the programmer's logic , You must define static variables in front of static code blocks . Because the execution of the two will be determined according to the order in which the code is written , The wrong order may affect your business code
JVM Initialization steps :
If this class has not been loaded and connected , The program loads and links the class first
If the direct parent of this class has not been initialized , First, initialize its immediate parent class
If there are initialization statements in the class , Then the system executes these initialization statements in turn
Active initialization :
Create an instance of a class , That is to say new The way
Accessing static variables of a class or interface , Or assign a value to the static variable
Calling static methods of a class
Reflection ( Such as Class.forName(“com.carl.Test”) )
Initializing a subclass of a class , The parent class will also be initialized
Java The class marked as the startup class when the virtual machine starts (JvmCaseApplication ), Use it directly java.exe Order it
Run a main class
Passive initialization :
Static fields that reference the parent class , Will only cause initialization of the parent class , Does not cause initialization of subclasses .
Define class array , Does not cause class initialization .
Of the reference class static final Constant , Does not cause class initialization ( If only static modification , It will cause this class to initialize ).
uninstall
After using the class , If the following conditions are met , Class will be unloaded :
1、 All instances of this class have been reclaimed , That is to say java There are no instances of this class in the heap
2、 Load the class ClassLoader Has been recovered
3、 Corresponding to this class java.lang.Class Object is not quoted anywhere , The Party of this class cannot be accessed anywhere through reflection
Law
If all the above three conditions are met ,jvm It will unload the class when the method area is garbage collected , The unloading process of a class is actually to clear the class information in the method area ,java The entire life cycle of a class is over . However, in general, the classes loaded by the startup class loader will not be unloaded , Our other two basic types of class loaders are unloaded only in rare cases
Class loader
Loading (Load) Stage : Gets the binary byte stream defined by the fully qualified name of the class , It needs to be done with class loader , seeing the name of a thing one thinks of its function , It's for loading Class Of documents
1、 Responsible for reading Java Byte code , Translates into java.lang.Class Class
2、 Class loaders are used in addition to loading classes , It can also be used to determine the class in Java Uniqueness in virtual machines
A class is unique in the same class loader (Uniqueness), In different kinds of loaders, classes with the same name are allowed
Of , The same name here refers to the fully qualified name . But in the whole JVM in , Even if all the names are the same , If the class loader does not
Same as , It still doesn't count as the same class , Unable to get instanceOf 、equals Etc
Classloader classification
Bootstrap ClassLoader: Responsible for loading $JAVA_HOME in jre/lib/rt.jar All in class or Xbootclassoath Option specified jar package
Extension ClassLoader: Responsible for loading java Some of the extensions in the platform jar package , Include $JAVA_HOME in jre/lib/*.jar or -Djava.ext.dirs Specify the package under the directory
App ClassLoader: Responsible for loading classpath Specified in the jar Package and Djava.class.path The classes in the specified directory and jar package
Custom ClassLoader: adopt java.lang.ClassLoader Custom loading of subclasses class, It belongs to the application customized according to its own needs classLoader, Such as tomcat,jboss
JVM Three features of the class loading mechanism
1、 Overall responsible for , When a classloader is responsible for loading a certain Class when , The Class Other things that are relied on and quoted Class It will also be
The class loader is responsible for loading , Unless it is shown that another classloader is used to load
2、 Parent delegation ,“ Parents delegate ” It refers to the subclass loader if it has not loaded the target class , First delegate the parent class loader to load the target class ,
Only when the parent class loader cannot find the bytecode file can it find and load the target class from its own class path ; The parent delegate alias is
It is called parent delegation mechanism .
" Parents delegate " Mechanism loading Class What is the specific process :
2.1、ClassLoader First of all, judge what to do Class Loaded or not , If loaded , Then return to Class object ; If not, entrust
Give the parent class loader .
2.2、 The parent class loader determines whether the Class, If loaded , Then return to Class object ; If not, entrust to
Grandfather class loader .
2.3、 And so on , Until the ancestor class loader ( Reference class loader ).
The ancestor class loader determines whether the Class, If loaded , Then return to Class object ; If not, try
2.4、 Look under its corresponding classpath class Bytecode file and load . If the load is successful , Then return to Class object ;
If the load fails , Delegate to the subclass loader of the ancestor class loader .
2.5、 The subclass loader of the ancestor class loader tries to find... From its corresponding class path class Bytecode file and load . If loaded
Successfully entered , Then return to Class object ; If the load fails , Delegate to the descendant loader of the ancestor class loader .
2.6、 And so on , Until the source ClassLoader.
2.7. Source ClassLoader Try to find... From its corresponding classpath class Bytecode file and load . If the load is successful , be
return Class object ; If the load fails , Source ClassLoader No longer delegate its subclass loader , Instead, it throws out often .
“ Parents delegate ” The mechanism is just Java The recommended mechanism , It's not a mandatory mechanism .
We can inherit java.lang.ClassLoader class , Implement your own classloader . If you want to keep the parental delegation model , Just
Should override findClass(name) Method ; If you want to break the parental delegation model , Can be rewritten loadClass(name) Method
3、 Caching mechanisms , The caching mechanism will ensure that all loaded Class Will be cached in memory , When you need to use a
Class when , The class loader first looks for the object from the memory cache Class, Only the cache does not exist , The system will read the corresponding
Binary data of , And turn it into Class object , Store in cache . That's why it's modified Class after , Must restart
JVM, Changes to the program will take effect . For a class loader instance , Classes with the same full name are loaded only once , namely loadClass
Method will not be called repeatedly ; This is why our class variables are initialized only once .
Break parental delegation
Parental delegation is not a mandatory model , And it will bring some problems . Like java.sql.Driver This thing .JDK Only one specification interface can be provided , Instead of providing an implementation . The implementation is provided by the actual database provider . The provider's library can't always put JDK In the catalogue
1、SPI(service Provider Interface) : such as Java from 1.6 It's got SPI Is to gracefully solve such problems ——JDK
Provide the interface , Suppliers provide services . When programmers code, they face interface programming , then JDK Can automatically find the right implementation
Java There are many interfaces defined in the core class library , And also gives the call logic for these interfaces , However, no real
present . What developers need to do is to customize an implementation class , stay META-INF/services Register implementation class information in , For the core
Class library usage . such as JDBC Medium DriverManager
边栏推荐
- PhpMyAdmin stage file contains analysis traceability
- php 迷宫游戏
- NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
- Go language web development series 25: Gin framework: using MD5 to verify the signature for the interface station
- HALCON联合C#检测表面缺陷——HALCON例程autobahn
- Unity render streaming communicates with unity through JS
- Go 1.16.4: purpose of go mod tidy
- Qt学习25 布局管理器(四)
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
- [combinatorics] permutation and combination (examples of combinatorial number of multiple sets | three counting models | selection problem | combinatorial problem of multiple sets | nonnegative intege
猜你喜欢
SQL Injection (POST/Search)
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
Logback log sorting
Use vscode to view hex or UTF-8 codes
Rasp implementation of PHP
Dlopen() implements dynamic loading of third-party libraries
Mastering the cypress command line options is the basis for truly mastering cypress
Qt学习22 布局管理器(一)
全局事件总线
GoLand 2021.1: rename the go project
随机推荐
Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
使用vscode查看Hex或UTF-8编码
Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
【BW16 应用篇】安信可BW16模组与开发板更新固件烧录说明
Qt学习23 布局管理器(二)
selenium 浏览器(1)
Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
Use vscode to view hex or UTF-8 codes
Bidirectional linked list (we only need to pay attention to insert and delete functions)
Logback log sorting
可编程逻辑器件软件测试
GoLand 2021.1.1: configure the multi line display of the tab of the open file
[technology development-24]: characteristics of existing IOT communication technology
php 迷宫游戏
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
Go language web development series 27: Gin framework: using gin swagger to implement interface documents
Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
核酸修饰的金属有机框架药物载体|PCN-223金属有机骨架包载Ad金刚烷|ZIF-8包裹阿霉素(DOX)
[技術發展-24]:現有物聯網通信技術特點
Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware