Java class loading mechanism

 12 minutes to read

java class loading mechanism

Class loading mechanism

The so -called class loading mechanism is that the JVM virtual machine loads the Class file to the memory, and the data is verified, resolved and initialized to form a Java type that virtual machines can directly use, that is, java.lang.class.

Class life cycle

The life cycles of class are mainly 7 stages of loading, verification, preparation, analysis, initialization, use, and uninstallation.

The process of loading includes the five stages: loading, verification, preparation, analysis, and initialization. In these five stages, the order of the four stages of loading, verification, preparation and initialization is certain, and the analysis phase is not necessarily. It can start after the initialization stage in some cases. This is to support Java. Binding during the runtime of language.

  • Class load: Find and load the binary data of the class
In the first stage of the class loading process, in the loading stage, the virtual machine needs to complete the following three things:

1. Through a full -limited name of a class to obtain the binary byte flow of its definition.

2. Translate the static storage structure represented by this byte running flow into the data structure of the method area.

3. Given a Java.lang.class object representing this class in the Java pile as the access entrance to these data in the method area.

Compared to other stages of class loading, the loading phase is the most controllable stage, because developers can use the class loader provided by the system to complete the loading, or customize their own class loader to complete the completion load.

After the loading phase is completed, the binary of the virtual machine is stored in the method area according to the format required by the virtual machine, and also creates an object of a java.lang.class class in the Java pile, so that it can pass the These data in the object access method area.

JVM specification allows the class loader to load it in advance when a certain class is expected to be used. If you encounter the lack of or errors in the .class file in the pre-loading process, the class loader must actively use the program for the first time in the program. When this class is only reported (linkageerror error), if this class has not been actively used by the program, then the type loader will not report errors.

Method of loading .class files

  1. Load directly from the local system
  2. Download .class files through the Internet
  3. Load the .class file from Zip, JAR and other archive files
  4. Extract .class file from a proprietary database
  5. Dynamically compiled Java source files to .class files

connect

Verification: Make sure the correctness of the class loaded

Verification is the first step in the connection phase. The purpose of this stage is In order to ensure that the information contained in the byte flow of the Class file meets the requirements of the current virtual machine, and it will not endanger the safety of the virtual machine itself. The verification phase will be roughly completed in 4 stages of inspection actions:

  1. File format verification: Verify whether the byte flow is in line with the specifications of the Class file format; for example: whether: whether the constant of the current virtual machine is within the current virtual machine’s processing range with 0xcafebaba, whether There are types that are not supported.

  2. metadata verification: Semantic analysis of the information described by byte code (Note: compare the semantic analysis of the Javac compilation phase) to ensure that the information described meets the requirements of the Java language specification; for example: whether this class is this class? There are father -in -law, except Java.lang.object.

  3. Bytecode verification: Through data flow and control flow analysis, determine the semantic semantics is legal and logical.

  4. Symbol reference verification: Make sure the parsing action can correctly execute.

The verification phase is very important, but it is not necessary. It has no effect on the running period of the program. If the cited class is repeatedly verified, you can consider using the -xverfynone parameter to close most of the class verification measures to shorten the virtual machine class Load time.

Preparation: allocate memory for the static variables of the class, and initialize it into the default value

The preparation phase is the stage of forming the initial value of the class variables for the class variables and the setting of the class variable, and these memory will be allocated in the method area.

There are the following points to pay attention to this stage:

  1. At this time, the memory allocation only includes a class variable (static), not an instance variable. The instance variable will be distributed in the Java heap as the object is instantiated.

  2. The initial value set here is usually the default zero value (such as 0, 0L, NULL, FALSE, etc.) defaults to the data type, instead of being explicitly given by the Java code.

You need to pay attention to the following points

  1. For basic data types, for class variables (static) and global variables, if it is not applied to it directly, the system will give it default zero value. For local variables, in use, in use It must be apparent to it before, otherwise it will not pass when compiled.

  2. For constants that are modified by static and final at the same time, they must be explicitly assigned to it when they declare, otherwise they will not pass when compiled; and constants that are only modified by Final can be explicitly assigned to it when the statement is declared. It can also be explicitly assigned to it during class initialization. In short, it must be explicitly assigned to it before use, and the system will not give it default zero value.

  3. For the reference type reference, such as array references, object references, etc., if it is not explicitly assigned to use it directly, the system will give it default zero value, that is, NULL.

  4. If there is no assignment to the elements in the array during the array initialization, the elements of the elements will be given the default zero value according to the corresponding data type.

  5. If there is a constantValue property in the field attribute table of the field, that is, at the same time, it is modified by final and static, then the value of the variable value at the preparation phase will be initialized to the value specified by the Constvalue property. STATIC FINAL constants put their results in the constant pool that calls it to call it

Analysis: Convert the symbol in the class to direct reference

The analysis phase is the process of reference the symbol references in the constant pool to direct reference. The parsing action is mainly for category or interfaces, field methods, interface methods, method types, method handles, and calling points. conduct. Symbol references are a set of symbols to describe the target, which can be any of the dough.

Direct reference is the handle of the handle of the target, relative offset or an indirect positioning of the target.

initialization

Initialization gives the correct initial value to the static variables of the class. The JVM is responsible for initializing the class, and the class variables are mainly initialized.

There are two ways to set the initial value setting of class variables in Java:

  1. Declaration class variable is the specified initial value

  2. Use static code blocks to specify the initial value of the class variable

Jvm initialization step

  1. If this class has not been loaded and connected, the program is loaded first and connected to this class

  2. If the direct parent class of this class has not yet been initialized, the preliminary initialization of its direct parent class

  3. If there are initialized sentences in the class, the system executes these initialized sentences in order

Class initialization timing: Only when the active use of the class can cause the class to initialize. The active use of the class includes the following six types:

1. Create instances, that is, the way of New

2. Access with a static variable of a class or interface, or assign a value to the static variable

3. Call the static method of the class

4, reflection (such as class.FORNAME ("")

5. Initialize a sub -class of a certain class, the parent class will be initialized

6. Java virtual machine is marked as a class class (java test) when starting, and directly use the java.exe command to run a certain class.

use

The interface of the data structure in the class interview method area is the data of the Heap area.

uninstall

Java virtual machines will end several situations in the life cycle

  1. The system.exit () method is executed

  2. The procedure is ended normally

  3. The program is terminated during the execution process

  4. Due to the error of the operating system, the process of the Java virtual machine is terminated

class loader

From the perspective of Java virtual machines, there are only two different types of loaders: startup class loaders: it uses C ++ to implement (here is limited to HOTSPOT, that is, the default virtual machine after JDK1.5, there are many other other. The virtual machine is implemented in Java language), which is part of the virtual machine itself; All other class loaders: These classes loaders are implemented by the Java language, independent of the virtual machine, and inherit the abstract java.lang.classloader, These class loaders need to load other classes after being loaded into memory from the startup class loader.

From the perspective of Java developers, the class loader can be roughly divided into the following three categories:

Start-up class loader: Bootstrap ClassLoader, responsible for loading under the path of JDK \ JRE \ lib (the same as the installation directory of JDK, the same below), or is specified by the-XBOOTCLASSPATH parameter, and it can be virtual machine The identified class library (such as RT.JAR, all the classes beginning with Java.Were loaded by Bootstrap Classloader). ** The startup class loader is not directly referenced by the Java program.*

Extension loader: Extension ClassLoader, the loader is implemented by Sun.Misc.launcher $ ExtClassLoader, which is responsible for loading JDK \ JRE \ Lib \ EXT directory, or by the path specified by the Java.ext.DIRS system variable. All class libraries (such as javax.*At the beginning), developers can directly use extension loaders.

Application class loader: Application classloader, this class loader is implemented by sun.misc.launcher $ appClassloader. It is responsible for loading the class specified by the user class (ClassPath). Developers can directly use this class to load them In the application, if there is no customized loader in the application, this is generally the default class loader in the program.

Applications are loaded with each other with these three types of loaders. If necessary, we can also add a customized class loader. Because the ClassLoader comes with JVM only knows the Java Class file that loads the standard from the local file system, if you write your own classloader, you can do the following:

1. Before executing unbelievable code, automatically verify digital signatures.

2. Dynamically create a customized construction class that meets the user’s specific needs.

3. Get Java Class from a specific place, such as the database and the network.

class loading

There are three ways to load classes:

1. Direction line to start the application by JVM initialization

2. Dynamically loaded through the class.Forname () method

3. Dynamic loading through classloader.loadClass () method dynamically

Class.Forname () and classloader.loadClass ()?

1. Class.Forname (): load the class .class files to JVM, and also explain the class to execute the static block in the class;

2. Classloader.loadClass (): Only one thing is to load the .class file to the JVM without executing the content in the static. Only in Newinstance will execute the static block.

3. Class.ForName (name, initialize, loader) with the function can also control whether to load the Static block. And only the newInstance () method is called to use the call constructor to create an object of the class.

JVM class loading mechanism

Responsible for, when a class loader is responsible for loading a certain class, the class that the class depends on and cited will be loaded by this type of loader, unless the display is displayed using another class loader to load it into Essence

The parent-class commission is entrusted, first let the parent class loader try to load this class. Only when the parent loader cannot load this class, try to load this class from your own class.

The cache mechanism, the cache mechanism will ensure that all the loaded Class will be cached. When a certain class needs to be used in the program, the class loader first find the class from the cache area. It will read the corresponding binary data of this class and convert it to the Class object to store it in the cache area. This is why you must restart the JVM after modifying the class, and the modification of the program will take effect

Double -parent appointment mechanism, if a class loader receives a request for class loading, it will not try to load this class by itself. The request should eventually be passed to the startup class loader on the top layer, Only when the parent loader fails to find the required class in its search range, that is, the loader cannot be completed, and the sub -loader will try to load the class by themselves.

Double-parent appointment advantage

1. The system class prevents multiple copies of the same byte code in the memory

2, ensure the safe and stable operation of the java program

Customized class loader

Under normal circumstances, we all use the system class loader directly. But sometimes, we also need to customize class loaders. For example, the application is to transmit the byte code of the Java class through the network. To ensure security, these bytecodes are encrypted. At this time, the system class loader cannot load it. In this way accomplish. The custom class loader is generally inherited from the classloader class. From the analysis of the LoadClass method above, we only need to rewrite the FindClass method.

The core of the customized class loader is the acquisition of bytecode files. If it is an encrypted bytecode, the file needs to be decrypted in this class.