Loading mechanism of Java class

Source: Internet
Author: User

1. What is class loading

Class loading refers to reading the binary data in the class's. class file into memory, placing it in the method area of the run-time data area, and then creating a Java.lang.Class object in the heap that encapsulates the data structure of the class within the method area. The final product loaded by a class is a class object located in the heap, which encapsulates the data structure of the class within the method area and provides the programmer with an interface to access the data structures within the method area.

The ClassLoader does not need to wait until a class is "first active" and then load it, and the JVM specification allows the ClassLoader to preload it when it is expected that a class will be used. If you encounter a missing or an error in a. class file during pre-loading, the ClassLoader must report an error (Linkageerror error) when the program first actively uses the class, and the class loader does not report an error if the class has not been actively used by the program.

How to load the. class file:

    • Load directly from the local system
    • Download. class files over the network
    • Loading. class files from archive files such as Zip,jar
    • Extract the. class file from the proprietary database
    • To dynamically compile a Java source file into a. class file
2, the life cycle of the class

The process of loading, validating, preparing, parsing, and initializing five stages of the class load. In these five phases, the order in which the four phases of loading, validating, preparing, and initializing occurs is deterministic, and the parsing phase is not necessarily, which in some cases can begin after the initialization phase, in order to support runtime bindings for the Java language (also known as dynamic binding or late binding). Also note that the stages here are started in order, rather than sequentially or in order, because these phases are usually mixed in a cross-section, often invoking or activating another phase during one phase of execution.

Load

To find and load the binary data of a class, loading is the first stage in the class loading process, and during the load phase, the virtual machine needs to complete the following three things:

    • Gets its defined binary byte stream through the fully qualified name of a class.
    • Converts the static storage structure represented by this byte stream into the run-time data structure of the method area.
    • A Java.lang.Class object representing this class is generated in the Java heap as a access entry to the data in the method area.

In contrast to other phases, the load phase (accurately, the action of getting the binary byte stream of a class during the load phase) is the most controllable phase, because the developer can either use the system-provided classloader to complete the load or customize its own classloader to complete the load.

When the load phase is complete, the binary byte stream outside the virtual machine is stored in the method area in the format required by the virtual machine, and an object of the Java.lang.Class class is created in the Java heap so that the data in the method area can be accessed through the object.

Verify

Validation: Ensure that the class being loaded is correct

The purpose of the verification is to ensure that the information contained in the byte stream of the class file conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself. The validation phase will roughly complete the 4-phase inspection action:

    • File Format verification: Verify that the byte stream conforms to the specification of the class file format, for example: whether to start with 0xCAFEBABE, whether the major and minor version numbers are within the processing range of the current virtual machine, and whether the constants in the constant pool have unsupported types.
    • Meta-data validation: Semantic analysis of the information described in bytecode (note: Comparing the semantic analysis of the JAVAC compilation phase) to ensure that the information it describes conforms to the requirements of the Java language specification, for example: Whether this class has a parent class, except Java.lang.Object.
    • Bytecode verification: Through data flow and control flow analysis, it is reasonable to determine that the program semantics are legal and logical.
    • Symbol Reference Validation: Ensures that parsing actions are performed correctly.

The validation phase is important, but not necessary, and it has no effect on the program runtime, and if the referenced classes are repeatedly validated, consider using the-xverifynone parameter to turn off most of the class validation measures to shorten the load time of the virtual machine class.

Get ready

Prepare: Allocates memory for static variables of a class and initializes it to a default value

The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, which are allocated in the method area. There are a few things to note about this phase:

    • In this case, the memory allocation consists of only class variables (static), not instance variables, and the instance variables are allocated to the Java heap as the object is instantiated.
    • The initial value set here is typically the default value of 0 for the data type (such as 0, 0L, NULL, FALSE, and so on), rather than being explicitly assigned to the value in Java code.

Suppose a class variable is defined as:public static int value = 3;

Then value the initial value of the variable after the preparation phase is 0, not 3, because no Java method has been executed at this time, and the value instruction assigned to 3 is stored in the class constructor <clinit> () method after the program is compiled, so the value An assignment of 3 is performed at the initialization stage.

Analytical

Parse: Converts a symbolic reference in a class to a direct reference

The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference, and the parsing action is primarily for a class or interface, a field, a class method, an interface method, a method type, a method handle, and a call Point qualifier 7 class symbol reference. A symbolic reference is a set of symbols that describe a target, which can be any literal.

A direct reference is a pointer directly to the target, a relative offset, or a handle that is indirectly anchored to the target.

Initialization

initialization, which assigns the correct initial value to the static variables of the class, the JVM is responsible for initializing the class, primarily initializing the class variables. There are two ways to set the initial value of a class variable in Java:

① declares that a class variable is a specified initial value
② specifying an initial value for a class variable using a static code block

JVM Initialization steps:

    1. If the class has not been loaded and connected, the program loads and connects the class first
    2. If the immediate parent class of the class has not been initialized, its immediate parent class is initialized first
    3. If there are initialization statements in the class, the system executes the initialization statements sequentially
3. Class Loader

Class loaders have hierarchical relationships such as:

From the developer's point of view, the ClassLoader can be categorized into the following three categories:

    • Start the ClassLoader: Bootstrap ClassLoader, which is responsible for loading the jdk\jre\lib (the JDK represents the JDK's installation directory, the same below), or the path specified by the-xbootclasspath parameter, and class libraries that can be recognized by virtual machines (such as Rt.jar, all java. classes that begin with bootstrap ClassLoader are loaded). The startup ClassLoader cannot be referenced directly by a Java program.
    • Extension class loader: Extension ClassLoader, which is implemented by Sun.misc.launcher$extclassloader, is responsible for loading the Jdk\jre\lib\ext directory, or all class libraries in the path specified by the JAVA.EXT.DIRS system variable (such as javax. Class), developers can use the extension class loader directly.
    • Application ClassLoader: Application ClassLoader, which is implemented by Sun.misc.launcher$appclassloader, is responsible for loading the class specified by the user class path (ClassPath). Developers can use the ClassLoader directly, if the application does not customize its own classloader, typically this is the default class loader in the program.
4. Loading of classes

There are three ways to load a class:

    1. The command line starts the application when the JVM initializes the load
    2. Dynamic loading via the Class.forName () method
    3. Dynamic loading via the Classloader.loadclass () method

Class.forName () and Classloader.loadclass () differences:

    • Class.forName (): In addition to loading the class's. class file into the JVM, static blocks in the class are also executed.
    • Classloader.loadclass (): The only thing to do is to load the. class file into the JVM, do not execute the contents of static, and only call Newinstance () to execute the static block.
    • Class.forName (name, initialize, loader) with the parameter function also controls whether static blocks are loaded. And only call the Newinstance () method using the call constructor to create the class object.
5. Parental assignment model

The workflow of the parent delegation model is that if a classloader receives a request for a class load, it does not attempt to load the class on its own, but instead delegates the request to the parent loader to complete, then up, so that all class load requests should eventually be passed to the top-level startup class loader. The load cannot be completed until the parent loader finds the required class in its search scope, and the child loader tries to load the class on its own.

Parent delegation Mechanism:

    1. When Appclassloader loads a class, it first does not attempt to load the class itself, but instead delegates the class load request to the parent ClassLoader Extclassloader to complete.
    2. When Extclassloader loads a class, it does not attempt to load the class on its own, but instead delegates the class load request to Bootstrapclassloader to complete.
    3. If the bootstrapclassloader fails to load (for example, the class is not found in $java_home/jre/lib), the extclassloader is used to try to load;
    4. If the Extclassloader also fails to load, the Appclassloader will be used to load, and if the Appclassloader also fails to load, an exception classnotfoundexception will be reported.

Parental delegation Model meaning:

    • System class prevents multiple copies of the same byte code in memory
    • Ensure safe and stable operation of Java programs

Permanent update of this article address: https://github.com/nnngu/LearningNotes/blob/master/JVM/02%20Java%E7%B1%BB%E7%9A%84%E5%8A%A0%E8%BD%BD% E6%9c%ba%e5%88%b6.md

Loading mechanism of Java class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.