当前位置:网站首页>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
边栏推荐
- Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
- Flutter dynamic | fair 2.5.0 new version features
- 【556. 下一个更大元素 III】
- 金属有机骨架MOFs装载非甾体类抗炎药物|ZIF-8包裹普鲁士蓝负载槲皮素(制备方法)
- Depth and breadth first traversal of tree (regardless of binary tree)
- Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
- JS continues to explore...
- Unity render streaming communicates with unity through JS
- 28:第三章:开发通行证服务:11:在配置文件中定义属性,然后在代码中去获取;
- UiO-66-COOH装载苯达莫司汀|羟基磷灰石( HA) 包裹MIL-53(Fe)纳米粒子|装载黄芩苷锰基金属有机骨架材料
猜你喜欢

There is nothing new under the sun. Can the meta universe go higher?

JVM系列——概述,程序计数器day1-1

Uio-66-cooh loaded bendamostine | hydroxyapatite (HA) coated MIL-53 (FE) nanoparticles | baicalin loaded manganese based metal organic skeleton material

Go language web development series 27: Gin framework: using gin swagger to implement interface documents

Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm

Multi person collaborative data annotation based on Baidu brain easydata from scratch

Qt学习25 布局管理器(四)

SQL Injection (POST/Search)
![[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心](/img/06/b71b505c7072d540955fda6da1dc1b.jpg)
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心

Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
随机推荐
GoLand 2021.1.1: configure the multi line display of the tab of the open file
Go language unit test 5: go language uses go sqlmock and Gorm to do database query mock
Solve MySQL 1045 access denied for user 'root' @ 'localhost' (using password: yes)
信创产业现状、分析与预测
Sequence table (implemented in C language)
交联环糊精金属有机骨架负载甲氨蝶呤缓释微粒|金属-有机多孔材料UiO-66负载黄酮苷类药物|齐岳
Rasp implementation of PHP
怎样删除对象的某个属性或⽅法
Nucleic acid modified metal organic framework drug carrier | pcn-223 metal organic framework encapsulated ad adamantane | zif-8 encapsulated adriamycin (DOX)
Leetcode-1175. Prime Arrangements
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
page owner特性浅析
Use and design of Muduo buffer class
Replace the GPU card number when pytorch loads the historical model, map_ Location settings
GoLand 2021.2 configure go (go1.17.6)
Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
How to promote the progress of project collaboration | community essay solicitation
Conversion function and explicit
Common network state detection and analysis tools