Fourth Chapter class loading mechanism

Source: Internet
Author: User

Note: This article mainly refers to the deep understanding of Java Virtual Machine (second edition)

Before looking at this article, first understand the JVM memory structure, see chapter I JVM Memory structure

1. Class loading process

    • Load the data from the Xxx.class file into the JVM memory from the description class
    • Validate, prepare, and parse these data (these three processes are always referred to as "links")
    • The data is initialized, resulting in a class object that can be used directly by the JVM

Attention:

    • The class loading process is done at run time .

2. Loading

    • Function: Load the data from the Xxx.class file into the JVM memory from the description class
    • Three things to do in this phase
      • Get a binary byte stream that defines this class by using the fully qualified class name of a class
      • Convert the static storage structure represented by this byte stream into the run-time data structure of the method area
      • Generates a Java.lang in the method area. class object, which serves as the access entry for various data of that class within the method area
    • Attention:
      • The completion of class loading is accomplished by fully qualified class names and class loaders (Classloadera instances), which are also identified by the two elements that identify an already loaded class
      • Interface, class: Name is " Fully qualified class name +classloader instance ID", this type of class is loaded by the ClassLoader that is located
      • Array: "[Base Type" or "[l reference type;"] (eg.byte[] bytes = new byte[512];//class named "[B"; object[] Objs = new object[10];//class named "[Ljava.lang.Object;" )
        • Note that the base type names are all capitalized (EG.BYTE:B), with two exceptions boolean:z;long:j
        • The array class is created directly by the JVM and its array elements are loaded by the ClassLoader

3. Verification

  • Four-part verification
    • File format validation: When a binary byte stream defining this class is obtained through the fully qualified class name of a class, verify that the byte stream satisfies the class file format (for example: The first is the magic number, whether the major or minor version number is within the current virtual machine processing range, i.e. whether the version is between the primary and the main, not loaded (This is why the lower version of the JDK is unable to perform the high-version JDK), and so on, after the test, perform the second thing in the "Loading" section, put the data into the method area and store
      • Format does not match: Java.lang.VerifyError
    • Metadata validation: Ensure that the metadata information for a class conforms to the Java language specification (for example: If this class is a generic class, does it implement all classes under its implementation interface)
      • For information about the metadata of a class, see chapter II, Javac compilation principle
    • Verifies the bytecode instruction of the method body, determines the order of instructions in accordance with the logic
    • Symbol Reference Validation:
      • Occurs during the parsing phase: the process of converting a symbolic reference to a direct reference
      • The validation of symbol references ensures that these symbolic references (attributes, methods, and so on) exist, and that they have the appropriate permissions (eg. The private method cannot be accessed by other classes)
        • Nosuchmethoderror, Nosuchfielderror, Illegalaccesserror
  • Attention:
    • The validation phase may be interspersed in other stages of class loading
    • -xverify:none: Close most of the verification operations, which we generally do not configure this parameter (that is, we will generally do the verification), because the class load occurs, but most of the class loading behavior occurs when the server is started, and actually does not affect our program run. Of course, if we manually call Class.forName (), This.getClass.getClassLoader (). LoadClass (), this will execute into this code when the class is loaded, but after all is a handful. Typically we use Class.forName () to introduce MySQL drivers, which is why the MySQL driver package was introduced in Maven when it was runtime.

4. Preparation

    • Role: allocating memory for class variables (these exist in method area allocations), setting class variable 0 values
    • Attention:
      • Allocates memory for class variables (allocates memory for static objects, which is how static variables are stored in the method area)
      • an instance variable in a class is allocated in the heap along with the creation of the object instance, and, of course , the base data type is pushed directly into the operand stack as the object is created .
      • assign a static variable a value of 0 (the default 0 value)(eg.static int x = 123;//this time x = 0, and x = 123 occurs during the initialization phase)
      • assign an initial value (expectation) for the final variable(eg.final int y = 456;//this time y = 456)

5. Analysis

    • Role: Symbolic references are converted to direct references
    • Symbol reference (compile time): stored in the constant pool of class file (see chapter III Class file structure and JAVAP use), only some names, no actual address
    • Direct reference (Runtime): In this phase, the symbolic reference is assigned the actual memory, and then the symbol reference is converted to a direct reference, stored in the run-time-constant pool
      • Chang: Concepts in the class file
      • Run a constant pool: a component of the method area within the JVM memory structure
    • Attention
      • This step does not necessarily occur before the initialize phase, but must be resolved before a symbol reference is used.

6. Initialization

    • Function: Execute static block (static{}), Initialize (as desired) static variable (eg.static int x = 123;//"prep" stage, x = 0; After "initialize", x = 123), Execute constructor
    • Time of Occurrence:
      • NEW: Execution Builder
      • The subclass invokes initialization, and if the parent class is not initialized, the parent class is initialized first (eg. subclass called "New parameterless constructor", first to execute "parameterless constructor" of the parent Class)
      • Reflection calls the class, and if the class is not initialized, it needs to be initialized first.
      • When the virtual machine starts, the class that contains the main () method is initialized
    • Note: static{} with the static variable initialization does not necessarily occur when the server starts (that is, does not necessarily occur when the class loads), if you want to achieve a container start, execute a code XXX, you can implement the class spring Initalizingbean, Rewrite the Afterpropertiesset () method under this interface to write the XXX code to the method .

Summarize:

    • Class loading process
      • Load first stage: Gets the binary byte stream that defines this class by using the fully qualified class name of a class
      • Validation first stage: file format validation
      • "Loading" the second stage: converting the static storage structure represented by this byte stream into the runtime data structure of the method area
      • "Validation" Phase II: meta-data validation
      • "Validation" Phase III: Bytecode directives for validating method bodies
      • "Ready" first stage: class variables allocating memory
      • "Ready" Phase II: Set class variable 0 value
      • "Validation" Phase IV: Symbol reference validation (following "parsing", only when "parsing" occurs)
      • "Parsing": symbol references are converted to direct references (not steps that must be preceded by "initialize")
      • Initialize: Not necessarily when, but always after load, validate, and prepare.
    • With regard to the validation section, we might suspect that since Javac has done a lot of validation in the "parsing" and "Semantic Analysis" sections, why is it validating when classes are loaded?
      • Javac does not do all the validation in the class loading section, for example: magic number Verification
      • Not all class files are generated by Javac, but also by third-party jars, even their own fake class

Fourth Chapter class loading mechanism

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.