当前位置:网站首页>Chapter 3: detailed explanation of class loading process (class life cycle)
Chapter 3: detailed explanation of class loading process (class life cycle)
2022-07-06 22:18:00 【Zhang Sanfeng learns from Dugu Jiujian】
The first 3 Chapter : Class loading process ( The life cycle of a class ) Detailed explanation
summary
stay Java in data type It is divided into Basic data type and Reference data type . The basic data type is pre-defined by the virtual machine , The reference data type needs to be loaded .( The class here is not a class in the narrow sense , It includes : Interface , annotation , enumeration )
according to Java Virtual machine specification , from class File to the class loaded into memory , Until the class is unloaded from memory , Its entire life cycle includes the following 7 Stages :
among , verification 、 Get ready 、 analysis 3 The parts are collectively called link (Linking)
From the use of classes in the program :
What we call loading completion includes **: load 、 link 、 After the three initialization stages are completed, the class enters the method area ** in
What we will talk about in the meeting is to explain according to five stages .
Interview questions of Dachang
The ant gold dress :
Describe the JVM load class The principle and mechanism of documents ? one side : Class loading process
Baidu :
Class load time
java Class loading process ?
sketch java Class loading mechanism ?
tencent :
JVM Middle class loading mechanism , Class loading process ?
sound of dripping water :
JVM Class loading mechanism
Meituan :
Java Class loading process
Describe the jvm load class The principle and mechanism of documents
JD.COM :
What is class loading ?
What triggers the loading of the class ? Let's talk about JVM The process of loading a class JVM What is the class loading mechanism of ?
Process one :Loading( load ) Stage
Load the completed operation
The understanding of loading
So called load , In short, it means that Java Class to load the bytecode file into machine memory , And build... In memory Java Prototypes of classes —— Class template object . So called class template object , Actually Namely Java Class in JVM A snapshot in memory .JVM The constant pool that will be parsed from the bytecode file 、 Class fields 、 Class methods and other information are stored in class templates , such JVM At run time, it can be obtained through the class template Java Any information in the class , Can be right Java Class's member variables are traversed , It can also be done Java Method call .( Class template , Is placed in the method area )
The mechanism of reflection is based on this basis . If JVM No will Java Class declaration information is stored , be JVM It can't be reflected at runtime .
Load the completed operation
Loading phase , in short , Find and load the binary data of the class , Generate Class Example .
When loading a class ,Java The virtual machine must complete the following tasks 3 thing :
- By the full name of the class ( Full class name , Package name + Class name ), Get the binary data stream of the class .
- The binary data stream of the parsing class is the data structure in the method area ( Java Class model )
- establish java.lang.Class Class , Indicates the type . As the access to all kinds of data of this class in method area ( Instances in heap space , Points to the instance template in the method area )
How to get binary stream
For binary streams of classes , Virtual machine can be generated or acquired in many ways .( As long as the bytecode read matches JVM Standard is enough )
- Virtual machines may pass file system Read into one class Postfix file ( Most common )
- Read in jar、 zip And so on , Extract class file .
- Binary data of classes stored in the database in advance
- Use similar to HTTP Agreements like that adopt Load on the network
- Generate a segment at run time Class And so on
After getting the binary information of the class ,Java The virtual machine will process the data , And eventually turn into a java.lang.Class Example .
If the input data is not ClassFile Structure , It will be thrown out. ClassFormatError.( The legal bytecode file is based on **cafebabe** start )
Class model and Class The location of the instance
The location of the class model
The loaded class is in JVM Create the corresponding class structure in , The class structure is stored in the method area (JDK1.8 Before : Forever ;JDK1.8 And after : Meta space ).()
Class The location of the instance
Class will .class After the file is loaded into the meta space , It's going to create one in the heap Java.lang .Class object , Used to encapsulate the data structure of the class in the method area , The Class Objects are created during class loading , Each class corresponds to a Class Object of type .(instanceKlass -->mirror:Class example )( The specific details will depend on 《 In depth understanding of Java virtual machine 》)
Instances of objects in heap space , Points to the class template object in the method area , As shown in the figure below .
The outside can pass through Order Class Class Object to get Class Object class data structure ( Reflection )
for example
/** * @author shkstart * @create 2020-09-11 17:39 * Process one : Loading phase * * adopt Class class , To obtain the java.lang.String Class , And print the method access identifier 、 The descriptor */
public class _1LoadingTest {
public static void main(String[] args) {
try {
Class clazz = Class.forName("java.lang.String");
// Gets all the methods declared by the current runtime class
Method[] ms = clazz.getDeclaredMethods();
for (Method m : ms) {
// Get modifier for method
String mod = Modifier.toString(m.getModifiers());
System.out.print(mod + " ");
// Get the return value type of the method
String returnType = m.getReturnType().getSimpleName();
System.out.print(returnType + " ");
// Get method name
System.out.print(m.getName() + "(");
// Get the parameter list of the method
Class<?>[] ps = m.getParameterTypes();
if (ps.length == 0) System.out.print(')');
for (int i = 0; i < ps.length; i++) {
char end = (i == ps.length - 1) ? ')' : ',';
// Get the type of parameter
System.out.print(ps[i].getSimpleName() + end);
}
System.out.println();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Further explanation
Class The constructor of a class is private , Only JVM Be able to create .
private Class(ClassLoader loader) {
// Initialize final field for classLoader. The initialization value of non-null
// prevents future JIT optimizations from assuming this final field is null.
classLoader = loader;
}
java.lang.Class An instance is an interface to access type metadata , It's also the key data for reflection 、 entrance . adopt Class Class provides the interface , You can get the... Associated with the target class .class The specific data structure in the file : Method 、 Fields, etc .
Loading of array class
The case of creating an array class is a little bit special , because The array class itself is not created by the class loader , But by the JVM Created directly at runtime as needed , but The element types of arrays still need to be created by class loaders . Create an array class ( Hereinafter referred to as A) The process of :
- If the element type of the array is Reference type , then Follow the defined loading process Recursive loading ( That is, load the reference data type in the array ) And create an array A Element type of ;
- JVM Use the specified element type and array dimension to create a new array class .
If the element type of an array is a reference type , The accessibility of array classes is determined by the accessibility of element types . Otherwise, the accessibility of the array class will be defined by default as public.( If basic data type , As if public Just go )
Process two :Linking( link ) Stage
link 1: Link phase Verification( verification )
Validation phase (Verification)
When the class is loaded into the system , Start linking , Validation is the first step in the link operation .
Its purpose is to ensure that the bytecode loaded is legal 、 Reasonable and standard .
The steps of verification are complicated , There are many projects to be verified , Broadly Java The virtual machine needs to do the following checks , As shown in the figure .
Overall description :
The content of verification covers the content of class data information Format validation 、 Semantic check 、 Bytecode verification , And symbol reference verification .
- among Format validation is performed in conjunction with the loading phase . After passing the verification , The class loader will successfully load the binary data information of the class into the method area .
- Validation operations other than format validation will be performed in the method area .
Although the verification in the link phase slows down the loading speed , But it avoids all kinds of checks when bytecode is running .( Sharpening a knife never misses a woodcutter )
Specify :
Format validation : Whether to count by magic 0xCAFEBABE start , Whether the major and minor version numbers are in the current Java Within the scope of virtual machine support , Whether each item in the data has the correct length, etc .
Java The virtual opportunity performs bytecode Semantic check , If it doesn't conform to the standard in semantics , The virtual machine will not be verified . such as :
- Do all classes have parent classes ( stay java in , except object Outside , All other classes should have parents )
- Whether some are defined as final Method or class of is overridden or inherited
- Whether a non abstract class implements all abstract methods or interface methods
- Whether there are incompatible methods ( For example, the signature of a method is different except for the return value , Everything else is the same , This method will make the virtual machine unable to start scheduling ;abstract Method in case , It can't be final Of course. )
Java The virtual machine will also Bytecode verification , Bytecode Verification is also the most complex process in the verification process . It tries to analyze the byte stream , Determine whether the bytecode can be executed correctly . such as :
- In the execution of bytecode , Whether it will jump to a command that doesn't exist
- Whether the call to the function passed the correct type of parameter
- Whether the assignment of variables is given the correct data type, etc
Stack mapping frame (StackMapTable) It's at this stage , Used to detect at a specific bytecode , Whether the local variable table and the stack of operands have the correct data type . But unfortunately ,100% It is impossible to judge whether a byte code can be executed safely , therefore , The process is just to check for predictable, obvious problems as much as possible . If you can't pass the inspection at this stage , The virtual machine will not load the class properly either . however , If you pass this stage of inspection , It doesn't mean that this class has no problem at all .
in front 3 In the second inspection , File format errors have been ruled out 、 Semantic errors and incorrect bytecode . But there is still no guarantee that the class is OK .
- The calibrator will also perform Verification of symbol reference .Class In its constant pool, the file records other classes or methods it will use through strings . therefore , In the validation phase , The virtual machine will check that these classes or methods really exist , And the current class has access to this data , If a required class cannot be found in the system , It will be thrown out. NoClassDefFoundError, If a method cannot be found , It will be thrown out. NoSuchMethodError.
This phase is only executed in the parsing phase .
link 2: Link phase Preparation( Get ready )
Preparation stage (Preparation), in short , For class ** Static variables ( Class variables )** Allocate memory , And initialize it to the default value .( Class loading phase , The initialization must be Class variables are static variables )
When a class passes validation , The virtual machine will enter the preparation phase . At this stage , The virtual machine allocates the corresponding memory space for this class , And set the default initial value .Java The default initial values of virtual machine for various types of variables are shown in the table .
Be careful :Java Does not support boolean type , about boolean type , The internal implementation is int , because int The default value of is 0 , So the corresponding , boolean The default value of is false.
- Fields that don't contain the basic data type here use static final The condition of embellishment , because final It will be allocated at compile time , The preparation phase will be explicitly assigned .
- In fact, whether static or non static, just use final modification , Its value has been determined during compilation .
- Note that initialization is not assigned to instance variables here , Class variables are assigned in the method area , And instance variables are assigned to along with the object Java In the pile .
- In this phase, there will not be initialization or code execution as in the initialization phase .
Source code
public class _2LinkingTest {
private static long id;//
private static final int num = 1; //
private final int result = 33; //
public static final String constStr = "CONST";
// public static final String constStr1 = new String("CONST");
public Object getObj(){
return null;
}
public void print1(){
System.out.println("hello");
}
}
Bytecode
public class _2LinkingTest {
private static long id;
private static final int num = 1;
private final int result = 33;
public static final String constStr = "CONST";
public _2LinkingTest() {
}
public Object getObj() {
return null;
}
public void print1() {
System.out.println("hello");
}
}
If you define a constant of a string in a literal way , It is also the direct display assignment in the preparation phase .
You can see constStr1 No assignment , There is no that ConstantValue
link 3: Link phase Resolution( analysis )
After the preparation phase is complete , It's in the parsing phase .
Analytic stage (Resolution), in short , Will class 、 Interface 、 Symbolic references to fields and methods are converted to direct references .
- A detailed description :
Symbolic references are literal references , It has nothing to do with the internal data structure and memory layout of the virtual machine . It's easy to understand that Class Class file , A lot of symbolic references are made through constant pools . But when the program actually runs , It's not enough to just quote symbols , For example, when print1ln() Method is called , The system needs to know the location of this method .
give an example : Output operation System.out. println() The corresponding bytecode :
invokevirtual #5 <java/io/PrintStream.println>
Take the method as an example ,Java The virtual machine prepares one for each class Method table , List all of its methods in the table , When you need to call a class's method , As long as you know the offset of this method in the method table, you can call this method directly . By parsing operations , The symbolic reference can be transformed into the position of the target method in the method table of the class , So that the method is successfully called .
- Summary
The so-called parsing is to turn the symbolic reference into a direct reference , That is to say Get class 、 Field 、 Method pointer or offset in memory . therefore , so to speak , If direct reference exists , Then it is certain that this class exists in the system 、 Methods or fields . but Only symbolic references exist , It is not certain that the structure must exist in the system .
however Java The virtual machine specification does not explicitly require that the parsing phase be executed in sequence . stay HotSpot VM in , load 、 verification 、 Preparation and initialization are performed in an orderly manner , But parsing in the link phase is often accompanied by JVM Do not execute... Until initialization is complete .
- Review of strings
Last , Let's take a look at CONSTANT_String Parsing . Because string plays an important role in program development , therefore , It is necessary for readers to understand String stay Java Processing in virtual machines . When in Java When using string constants directly in code , Will appear in the class CONSTANT_String, It represents a string constant , And will reference a CONSTANT_UTF8 Constant item for . stay Java In the constant pool running inside the virtual machine , Will maintain a string detention table (intern), It will save all the string constants that have appeared without duplicates . As long as CONSTANT_String All strings in the form will also be in this table . Use String.intern() Method can get the reference of a string in the detention table , Because there are no duplicates in this table , So any literal string String.intern() Method returns are always equal .( In fact, it is the related interview question of string learned before )
Process 3 :Initialization( initialization ) Stage
Initialization phase , in short , Give the class the correct initial value for its static variables .
- A detailed description
Class initialization is the last stage of class loading . If there is no problem with the previous steps , Then the presentation class can be successfully loaded into the system . here , Class will start executing Java Bytecode .( namely : It's time to initialize , To actually start executing the Java Program code .)
The important work in the initialization phase is to execute Class ( Class constructor method ):<clinit>() Method ..
- This method can only be used by Java Generated by the compiler and JVM call , Program developers cannot customize a method with the same name , Even more can't be directly in Java This method is invoked in the program. , Although the method is also composed of bytecode instructions .
- It's an assignment statement by a static member of the class as well as static Statement block merging results in .
Assign values to static variables or code blocks
- explain
2.1 Before loading a class , The virtual machine will always try to load the parent class of this class , therefore Of the parent class <clinit> Always in the son <clinit> Called before . in other words , Of the parent class static Block priority is higher than subclass .
formula : By father and son , Static first .
Parent class
public class _3InitializationTest {
public static int id = 1;
public static int number;
static {
number = 2;
System.out.println("father static{}");
}
}
Subclass
public class _4SubInitialization extends _3InitializationTest {
static{
number = 4; // Use here number attribute , Must have been loaded in advance , So you must load the parent class first
System.out.println("son static{}");
}
public static void main(String[] args) {
System.out.println(number);
}
}
Output results
father static{
}
son static{
}
4
- 2 Java The compiler does not generate for all classes <clinit>() Initialization method . Which classes are compiled into bytecode , The bytecode file will not contain <clinit>() Method
- There is no No, Declare any Class variables , either Static code block when
- Declare class variables in a class , however It's not clear Use initialization statements of class variables and static code blocks to When performing initialization
- A class contains static final Modify the basic data type of the field , These class field initialization statements use compile time constant expressions
static And final It's a problem of collocation
explain : Use static + final The operation of the explicit assignment of the modified field , At which stage is the assignment made ?
situation 1: In the preparation phase of the link phase
situation 2: In the initialization phase <clinit>() Assignment in
Conclusion :
In the link phase of the preparation phase of the assignment situation :
- For fields of basic data types , If you use static final modification , be Explicit assignment ( Directly assign constants , Instead of calling methods ) Usually in Link phase The preparation process Conduct , If it's just static Decoration is in the initialization stage (<clinit>) assignment
- about String Come on , If you use Literal Method assignment , Use static final Embellished words , Then the explicit assignment is usually in ** The preparation of the link stage **
- Not used final modification , Consider the initialization phase
In the initialization phase <clinit>() In the case of assignment in :
Excluding the above assignment in the preparation phase .** The final conclusion : Use static + final modification , And display assignment No method or constructor calls are involved Basic data type or String Explicit assignment of type , It's in the link stage The preparation process .** In addition, they are all carried out in the initialization process .
public class _6InitializationTest2 {
public static int a = 1;// In the initialization phase <clinit>() Assignment in
public static final int INT_CONSTANT = 10;// In the preparation phase of the link phase
public static final Integer INTEGER_CONSTANT1 = Integer.valueOf(100);// In the initialization phase <clinit>() Assignment in
public static Integer INTEGER_CONSTANT2 = Integer.valueOf(1000);// In the initialization phase <clinit>() Assignment in , This may be due to the call Integer
public static final String s0 = "helloworld0";// In the preparation phase of the link phase
public static final String s1 = new String("helloworld1");// In the initialization phase <clinit>() Assignment in
public static String s2 = "helloworld2";
public static final int NUM1 = new Random().nextInt(10);// In the initialization phase <clinit>() Assignment in
}
<clinit> Bytecode file
0 iconst_1
1 putstatic #2 <com/atguigu/java/_6InitializationTest2.a> // Here you can see a It is copied in the initialization phase
4 bipush 100
6 invokestatic #3 <java/lang/Integer.valueOf>
9 putstatic #4 <com/atguigu/java/_6InitializationTest2.INTEGER_CONSTANT1> // It can be seen that the assignment is in the preparation stage
12 sipush 1000
15 invokestatic #3 <java/lang/Integer.valueOf>
18 putstatic #5 <com/atguigu/java/_6InitializationTest2.INTEGER_CONSTANT2> // It can be seen that the assignment is in the preparation stage
21 new #6 <java/lang/String>
24 dup
25 ldc #7 <helloworld1>
27 invokespecial #8 <java/lang/String.<init>>
30 putstatic #9 <com/atguigu/java/_6InitializationTest2.s1>
33 ldc #10 <helloworld2>
35 putstatic #11 <com/atguigu/java/_6InitializationTest2.s2>
38 new #12 <java/util/Random>
41 dup
42 invokespecial #13 <java/util/Random.<init>>
45 bipush 10
47 invokevirtual #14 <java/util/Random.nextInt>
50 putstatic #15 <com/atguigu/java/_6InitializationTest2.NUM1>
53 return
static final The basic data type of decoration is to assign values in the initialization stage
about String Come on , If you use Literal Method assignment , Use static final Embellished words , Then the explicit assignment is usually in ** The preparation of the link stage **, If it's not literal , It is assigned in the initialization stage .
21 new #6 <java/lang/String>
24 dup
25 ldc #7 <helloworld1>
<client>() Thread security
This is the following deadlock situation , initialization A Load again when B, initialization B Load again when A
Review the four conditions of deadlock
- Mutually exclusive : The resource must be in unshared mode , That is, only one process at a time can use . If another process requests the resource , Then you must wait until the resource is released .
- Take possession and wait : A process should occupy at least one resource , And wait for another resource , And the resource is occupied by other processes .
- non-preemptive : Resources can't be preempted . Only after the process holding the resource completes the task , That resource will be released .
- Loop waiting for : There is a set of waiting processes
{P0, P1,..., Pn}
,P0
Waiting resources areP1
occupy ,P1
Waiting resources areP2
occupy ,…,Pn-1
Waiting resources arePn
occupy ,Pn
Waiting resources areP0
occupy .
The following code will deadlock
class StaticA {
static {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
// Initializing A When , To load the B
Class.forName("com.atguigu.java1.StaticB");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("StaticA init OK");
}
}
class StaticB {
static {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
// Initializing B Load when you need to A
Class.forName("com.atguigu.java1.StaticA");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("StaticB init OK");
}
}
public class StaticDeadLockMain extends Thread {
private char flag;
public StaticDeadLockMain(char flag) {
this.flag = flag;
this.setName("Thread" + flag);
}
@Override
public void run() {
try {
Class.forName("com.atguigu.java1.Static" + flag);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(getName() + " over");
}
public static void main(String[] args) throws InterruptedException {
StaticDeadLockMain loadA = new StaticDeadLockMain('A');
loadA.start();
StaticDeadLockMain loadB = new StaticDeadLockMain('B');
loadB.start();
}
}
Class initialization : Active use vs Passive use
Java Programs use classes in two ways : Active use and passive use .
Active classes will call <clinit>, Passive use of classes will not call <clinit>
Active use
Class Only You must For the first time to use Will be loaded ,Java Virtual machines don't load unconditionally Class type .Java Virtual machine rules , Before a class or interface is first used , It has to be initialized . I mean " Use ", Refer to Active use , There are only a few cases of active use :( namely : If the following happens , The class is initialized . And the load before the initialization operation 、 verification 、 The preparation is complete .)
- When creating an instance of a class , For example, use new keyword , Or by reflection 、 clone 、 Deserialization .
- When calling a static method of a class , That is, when bytecode is used invokestatic Instructions .
- When using classes 、 Interface (final Special consideration ), such as , Use getstatic perhaps putstatic Instructions .( Corresponding access variables 、 Assignment variable operation )
- When using java.lang.reflect When a method in a package reflects a method of a class . such as : Class.forName(" com.atguigu.java.Test")
- When initializing a subclass , If it is found that its parent class has not been initialized , You need to trigger the initialization of its parent class first .
- If an interface is defined default Method , Then directly or indirectly implement the initialization of the interface class , The interface is initialized before it .
- When the virtual machine starts , The user needs to specify a main class to execute ( contain main() Method type ), Virtual opportunity initializes the main class first .
- When first called MethodHandle When an instance , Initialize the MethodHandle Point to the method Class .( It involves analysis
REF_getStatic、REF_putStatic、REF_invokeStatic The class corresponding to the method handle )
in the light of 5, Additional explanation :
When Java When the virtual machine initializes a class , Require that all of its parent classes have been initialized , But this rule doesn't apply to interfaces .When initializing a class , It doesn't initialize the interface it implements first
When initializing an interface , It doesn't initialize its parent interface first
therefore , A parent interface is not initialized because of the initialization of its child interface or implementation class . Only when the program first uses static fields for a specific interface , Will cause initialization of this interface .
Passive use
In addition to the above, it belongs to active use , Other situations belong to Passive use . Passive use does not cause class initialization .
in other words : It's not a class that appears in the code ! It will be loaded or initialized . If the conditions for active use are not met , Class will not initialize .
When accessing a static field , Only the class that actually declares this field will be initialized .
- When a static variable of a parent class is referenced by a child class , Does not cause subclass initialization
Define class references through arrays , Initialization of this class will not be triggered
Reference constants do not trigger initialization of this class or interface . because Constants have been explicitly assigned at the linking stage 了 .
call ClassLoader Class loadClass() Method to load a class , It's not an active use of classes , Does not cause class initialization .
Actively use code samples
Code example :
- Deserialization leads to active use
// Deserialization process :( verification )
@Test
public void test2() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("order.dat"));
Order order = (Order) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Calling static methods leads to active use
- Active call in interface
interface CompareA {
public static final Thread t = new Thread() {
{
System.out.println("CompareA The initialization ");
}
};
public static final int NUM1 = 1; // 1
// public static final int NUM2 = new Random().nextInt(10); //CompareA The initialization 1
}
@Test
public void test2() {
System.out.println(CompareA.NUM1);
// System.out.println(CompareA.NUM2);
}
CompareA Bytecode
0 new #1 <com/atguigu/java1/CompareA$1>
3 dup
4 invokespecial #2 <com/atguigu/java1/CompareA$1.<init>>
7 putstatic #3 <com/atguigu/java1/CompareA.t>
10 return
It's this new #1 In fact, that is new Thread, Jump down
0 aload_0
1 invokespecial #1 <java/lang/Thread.<init>>
4 getstatic #2 <java/lang/System.out>
7 ldc #3 <CompareA The initialization >
9 invokevirtual #4 <java/io/PrintStream.println>
12 return
So it can be verified , As long as it appears CompareA The initialization
It means that the interface is initialized , That is, active use .
Use -XX:+TraceClassLoading
Parameter print class loading information
Use code examples passively
Passive use of classes , That is, class initialization will not be performed , That is, it will not call <clinit>()
- When a static variable of a parent class is referenced by a child class , Does not cause subclass initialization
@Test
public void test1(){
System.out.println(Child.num);
}
class Child extends Parent{
static{
System.out.println("Child The initialization process ");
}
}
class Parent{
static{
System.out.println("Parent The initialization process ");
}
public static int num = 1;
}
Output results
Parent The initialization process
1
- Define class references through arrays , Initialization of this class will not be triggered
@Test
public void test2(){
Parent[] parents = new Parent[10];
}
- Reference constants do not trigger initialization of this class or interface . Because constants are explicitly assigned in the link phase .
The variable value is not added final modification , It will trigger <clinit>, This is assigned in the initialization phase .
@Test
public void test1(){
System.out.println(Person.NUM); // Will trigger <clinit>
}
class Person{
static{
System.out.println("Person Class initialization ");
}
public static int NUM = 1;// In the preparation phase of the link process, it is assigned as 1 了 .
public static final int NUM1 = new Random().nextInt(10);// The assignment operation at this time needs to be performed in <clinit>() In the implementation of
}
Variable value plus final modification , Will it trigger <clinit>, Because the value of this variable has been assigned in the preparation stage of the link stage .
@Test
public void test1(){
System.out.println(Person.NUM); // Not trigger <clinit>
}
class Person{
static{
System.out.println("Person Class initialization ");
}
public static final int NUM = 1;// In the preparation phase of the link process, it is assigned as 1 了 .
public static final int NUM1 = new Random().nextInt(10);// The assignment operation at this time needs to be performed in <clinit>() In the implementation of
}
- call ClassLoader Class loadClass() Method to load a class , It's not an active use of classes , Does not cause class initialization .
@Test
public void test3(){
try {
Class clazz = ClassLoader.getSystemClassLoader().loadClass("com.atguigu.java1.Person");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Process 4 : Class Using( Use )
Any type must have experienced complete load 、 Linking and initialization 3 A class loading step . Once a type has successfully experienced this 3 After one step , then “ everything , Only east wind ”, Just waiting for developers to use .
Developers can access and call its static class member information in the program ( such as : Static field 、 Static methods ), Or use new Keyword to create an object instance for .
Process five : Class is written in Unloading( uninstall )
class 、 Class loader 、 The reference relationship between instances of a class
In the internal implementation of the class loader , Use one Java Collection to hold references to the loaded classes ( Because a class loader may load multiple classes ). On the other hand , One Class Object always references its classloader , call Class Object's getClassLoader() Method , can Get its classloader . thus it can be seen , Representing a class Class Between the instance and its class loader is Two way Association .
An instance of a class always refers to Class object . stay Object Class getClass() Method , This method returns Class References to objects . Besides , be-all Java Class has a static property class, It refers to the Class object .
The life cycle of a class
When Sample Class quilt load 、 Linking and initialization after , Its life cycle begins . When representatives Sample Class Class Object is no longer referenced , That is not to be touched in time ,Class The object ends its life cycle ,Sample Class data in the method area will also be unloaded , So it's over Sample The life cycle of a class .( Pay attention to this Class The object is in the method area , Namely Class template object )
When does a class end its life cycle , It depends on what represents it Class When does an object end its lifecycle .
Algorithm to determine whether it is garbage (GC Algorithm ), There are two kinds of : Reference counting algorithm ( Causes circular references , Can't clean up ) And reachability analysis algorithm (HotSpot VM use )
review : Garbage collection in method area
There are two parts of garbage collection in the method area : Obsolete constants and unused types in the constant pool .
HotSpot The constant pool recycling strategy of virtual machine is very clear , As long as the constants in the constant pool are not referenced anywhere , Can be recycled .
Determine whether a constant is “ abandoned ” It's still relatively simple , To determine whether a type belongs to “ Classes that are no longer used ” The conditions are more stringent . The following three conditions need to be satisfied at the same time :
- All instances of this class have been reclaimed . That is to say Java There are no instances of this class and any of its derived subclasses in the heap .
- The classloader that loads this class has been recycled . This condition is unless it is a well-designed alternative class loader scenario , Such as OSGi、3SP And so on , Otherwise, it's usually hard to achieve .
- Corresponding to this class java.lang.Class The object is not referenced anywhere , The methods of the class cannot be accessed anywhere by reflection .
Java Virtual machines are allowed to recycle useless classes that meet the above three conditions , This is just saying “ Allowed ”, Not like the object , If there is no reference, it will be recycled .( Obvious , Because the heap space or method area reaches the threshold or is full GC)
Class
(1) The type loaded by the bootloader cannot be unloaded during the entire runtime (jvm and jls standard )
(2) Types loaded by system class loaders and extension class loaders are less likely to be unloaded during runtime , Because the instance of system class loader or extension class can be accessed directly or indirectly during the whole running period , It achieves unreachable It's very unlikely .
(3) The type loaded by the developer defined class loader instance can only be unloaded in a very simple context , And it can only be done with the help of mandatory call to the garbage collection function of virtual machine . It can be expected that , In a slightly more complex application scenario ( such as : Most of the time, users use caching strategy to improve system performance when developing custom class loader instances ), The loaded types are also less likely to be unloaded during runtime ( At least the time of unloading is uncertain ).
Synthesize the above three points , The probability of a loaded type being unloaded is very small, at least the time of unloading is uncertain . At the same time, we can see that , When developers develop code , You should not make any assumptions about the type of virtual machine , To achieve specific functions in the system .
边栏推荐
- 12、 Start process
- C#实现水晶报表绑定数据并实现打印4-条形码
- [线性代数] 1.3 n阶行列式
- China 1,4-cyclohexanedimethanol (CHDM) industry research and investment decision-making report (2022 Edition)
- 保存和检索字符串
- Unity3D学习笔记6——GPU实例化(1)
- Xiaoman network model & http1-http2 & browser cache
- 微信红包封面小程序源码-后台独立版-带测评积分功能源码
- Notes de développement du matériel (10): flux de base du développement du matériel, fabrication d'un module USB à RS232 (9): création de la Bibliothèque d'emballage ch340g / max232 SOP - 16 et Associa
- 二叉(搜索)树的最近公共祖先 ●●
猜你喜欢
硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
[daily] win10 system setting computer never sleeps
BarcodeX(ActiveX打印控件) v5.3.0.80 免费版使用
C # réalise la liaison des données du rapport Crystal et l'impression du Code à barres 4
Powerful domestic API management tool
GPS从入门到放弃(十七) 、对流层延时
Leetcode question brushing (XI) -- sequential questions brushing 51 to 55
Method return value considerations
Write a rotation verification code annotation gadget with aardio
GPS du début à l'abandon (XIII), surveillance autonome de l'intégrité du récepteur (raim)
随机推荐
[sdx62] wcn685x will bdwlan Bin and bdwlan Txt mutual conversion operation method
GPS from getting started to giving up (XX), antenna offset
Oracle Performance Analysis 3: introduction to tkprof
Wechat red envelope cover applet source code - background independent version - source code with evaluation points function
Codeforces Round #274 (Div. 2) –A Expression
Oracle control file and log file management
HDU 2008 数字统计
Mongodb (III) - CRUD
GPS from getting started to giving up (XI), differential GPS
HDU 4912 paths on the tree (lca+)
Memorabilia of domestic database in June 2022 - ink Sky Wheel
China 1,4-cyclohexanedimethanol (CHDM) industry research and investment decision-making report (2022 Edition)
第3章:类的加载过程(类的生命周期)详解
Classic sql50 questions
UNI-Admin基础框架怎么关闭创建超级管理员入口?
3DMax指定面贴图
Realization of epoll reactor model
Leetcode learning records (starting from the novice village, you can't kill out of the novice Village) ---1
GPS从入门到放弃(十八)、多路径效应
HDU 2008 digital statistics