Loading mechanism for Java classes

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 an object in the heap java.lang.Class that encapsulates the data structure of the class within the method area. The final product loaded by the class is the object that is located in the heap Class , which Class encapsulates the data structure of the class within the method area, and provides the Java programmer with an interface to access the data structures within the method area.

{:. Center}

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 will not report an error if the class has not been actively used by the program

How to load A. class file


2, the life cycle of the class

{:. Center}

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 become dynamic or late bound). 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

The first stage of the class loading process is to find and load a class's binary data load, 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.
    • An object representing this class is generated in the Java heap java.lang.Class as an access point to the data in the method area.

In contrast to other stages of class loading, the load phase (accurately, the action of getting the binary byte stream of a class during the load phase) is the strongest stage, because developers can either use the system-provided classloader to complete the load or customize their 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 class is created in the Java heap so that the java.lang.Class data in the method area can be accessed through the object.

Connection

Validation: Ensure that the class being loaded is correct

Validation is the first step in the connection phase, which is designed to ensure that the information contained in the byte stream of a 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 validation: Verify that the byte stream conforms to the specification of the class file format, such as whether the 0xCAFEBABE constants in the constant pool have unsupported types with the beginning and the primary and secondary version numbers within the processing range of the current virtual machine.
    • 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 -Xverifynone parameters to turn off most of the class validation measures to shorten the load time of the virtual machine class.

Prepare: Assign memory to the class 静态变量分 and initialize 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:

    • 1. This time memory allocation includes only class variables (static), not instance variables, and instance variables are allocated to the Java heap as objects are instantiated when the object is instanced.
    • 2, the initial value set here is usually the default value of the data type 0 (such as 0, 0L, NULL, FALSE, etc.), rather than being explicitly assigned in the Java code value.

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

Then the initial value of the variable value after the prep phase is 0, not 3, because no Java method has yet started executing, and the instruction to assign value 3 public static is stored in the class constructor method after the program is compiled <clinit>() . So an action that assigns value to 3 will not be executed until the initialization stage.

Here are a few more points to note:

  • For basic data types, for class variables (static) and global variables, which are used directly if they are not explicitly assigned to them, the system assigns them a default value of 0, and for local variables, they must be explicitly assigned before they are used, otherwise the compilation does not pass.
  • Constants that are both static and final modified must be explicitly assigned at the time of declaration, or not at compile time, whereas only final-modified constants can be explicitly assigned at the time of declaration, or they can be explicitly assigned when the class is initialized, in summary, You must assign a value to it explicitly before you use it, and the system does not give it a default value of 0.
  • For reference data type reference, such as an array reference, an object reference, and so on, if it is not explicitly assigned and is used directly, the system assigns it a default value of 0, or null.
  • If no values are assigned to elements in the array at initialization, the elements will be given a default value of 0 based on the corresponding data type.
    • 3. If a property exists in the field attribute table of a class field, that is ConstantValue both final and static, the value of the variable in the prepare phase is initialized to the values specified by the Constvalue property.

Assume that the above class variable value is defined as: public static final int value = 3 ;

At compile time, Javac will generate the Constantvalue property for value, and the virtual machine will ConstantValue assign value 3 based on the setting in the prepare phase. We can understand that the static final constant puts its result in the constant pool of the class that called it at compile time

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, first initialize its immediate parent class
    • 3, if the class has initialization statements, then the system executes these initialization statements in turn

Class initialization time: The class is initialized only when the class is actively used, and the active use of the class includes the following six types:

    • Create an instance of the class, that is, the new way
    • Access a static variable for a class or interface, or assign a value to the static variable
    • To invoke a static method of a class
    • Reflection (e.g. Class.forName(“com.shengsiyuan.Test”) )
    • Initializes a subclass of a class, its parent class is also initialized
    • A class () that is marked as the startup class when the Java Virtual machine starts Java Test , and java.exe runs a main class directly using the command

End Life cycle

In the following scenarios, the Java Virtual machine will end the life cycle

    • Implemented the System.exit() method
    • End of normal execution of the program
    • The program encountered an exception or error during execution and terminated abnormally
    • Java Virtual machine process terminated due to operating system error



Links: https://www.imooc.com/article/25978
Source: MU-Class Network
This article original published in Mu class network, reproduced please indicate the source, thank you for your cooperation

Loading mechanism for Java classes

Related Article

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.