Chapter 4 class loading mechanism and Chapter 4 loading mechanism

Source: Internet
Author: User

Chapter 4 class loading mechanism and Chapter 4 loading mechanism

Note: This article is mainly based on the "deep understanding of Java Virtual Machine (version 2)"

Before reading this article, you must first understand the JVM memory structure. For details, see Chapter 1 JVM memory structure.

1. class loading process

  • Load description class data from xxx. class file to JVM memory
  • Verify, prepare, and parse the data (these three processes are collectively referred to as "Links ")
  • Initialize the data to form a Class object that can be directly used by JVM.

Note:

  • The class loading process is completed at runtime.

 

2. Load

  • Purpose: load the description class data from the xxx. class file to the JVM memory.
  • This stage completes three tasks
    • Obtains the binary byte stream that defines this class by using the fully qualified class name of a class.
    • Converts the static storage structure represented by this byte stream into the runtime data structure of the method zone.
    • Generate a java. lang. Class Object in the Method Area, which serves as the access point for various data of the Class in the method area.
  • Note:
    • Class loading is completed by fully qualified class names and classloaders (ClassLoaderA instances). These two elements also identify a loaded class.
    • Interface and class: The name is "fully qualified class name + ClassLoader instance ID". Classes of this type are loaded by the ClassLoader.
    • Array: "[basic type" or "[L reference type;" (eg. byte [] bytes = new byte [512]; // The class name is "[B"; Object [] objs = new Object [10]; // The class name is "[Ljava. lang. object ;")
      • Note that the basic type names are all capitalized (eg. byte: B), with two exceptions: boolean: Z; long: J
      • An array class is directly created by JVM, and its array elements are loaded by the class loader.

 

3. Verification

  • Four-part Verification
    • File Format verification: after obtaining the binary byte stream that defines this class through the full-qualified class name of a class, check whether the byte stream meets the format of the class file (for example, the first is the magic number, whether the Primary and Secondary versions are within the processing range of the current virtual machine, that is, whether the version is between the primary and secondary versions, the higher version than the primary version does not load (this is why the lower version jdk cannot execute the higher version jdk), and so on). After the test, the second thing in the "LOAD" section is executed, store data in the Method Area
      • Invalid format: java. lang. VerifyError
    • Metadata verification: ensure that the metadata information of a class complies with the java language specifications (for example, if this class is a common class, whether all classes under its implementation interface are implemented)
      • For more information about the class metadata, see Chapter 2 Javac compilation principles
    • Verify the bytecode instruction of the method body and confirm that the instruction sequence conforms to the logic.
    • Symbol reference verification:
      • Occurs in the parsing phase: the process of converting a symbolic reference to a direct reference
      • Verify the symbolic references to ensure that these symbolic references (attributes, methods, etc.) exist and have corresponding permissions (eg. Ensure that private methods cannot be accessed by other classes)
        • NoSuchMethodError, NoSuchFieldError, IllegalAccessError
  • Note:
    • The verification phase may be interspersed with other stages of class loading.
    • -Xverify: none: Disable most verification operations. We generally do not configure this parameter (that is, we will still perform verification) because although class loading occurs during runtime, however, most of the class loading behaviors occur when the server is started. In fact, the program running is not affected. Of course, if we manually call the Class. forName (), this. getClass. getClassLoader (). loadClass (), this will load the class when the code is executed, but it is a minority after all. Generally, we use Class. forName () to introduce the MySQL driver. That is, when the MySQL driver package is introduced in maven, its scope is the reason of runtime.

 

4. Preparation

  • Purpose: allocate memory for class variables (which are allocated in the Method Area) and set the zero value of class variables.
  • Note:
    • Allocate memory for class variables (allocate memory for static objects, which is the principle of storing static variables in the Method Area)
    • The instance variables in the class will be allocated to the heap along with the creation of the object instance. Of course, if the basic data type is used, the instance variables will be directly pushed to the operand stack as the object is created.
    • Assign a zero value for the static variable (default zero value) (eg. static int x = 123; // At this time x = 0, while x = 123 occurs in the "initialization" phase)
    • Assign an initial value (expected value) to the final variable (eg. final int y = 456; // at this time, y = 456)

 

5. Analysis

  • Purpose: convert a symbolic reference to a direct reference.
  • Symbol reference (during compilation): it is stored in the constant pool of the class file (See Chapter 3 class file structure and javap usage). It has only some names and has no actual address.
  • Direct reference (runtime): in this phase, the actual memory is allocated for the symbol reference, and then the symbol reference is converted to direct reference, which is stored in the runtime constant pool.
    • Constant pool: concepts in the class file
    • Runtime frequent volume pool: an integral part of the Method Area in the JVM Memory Structure
  • Note:
    • This step may not occur before the "initialization" phase, but must be resolved before a symbolic reference is used.

 

6. Initialization

  • Purpose: Execute static blocks (static {}) and initialize static variables (eg. static int x = 123; // "after preparation", x = 0; "after initialization", x = 123), execute the constructor
  • Occurrence time:
    • New: Execution Constructor
    • The subclass calls initialization. If the parent class is not initialized, the parent class must be initialized first (eg. if the subclass calls "new no-argument constructor", the "no-argument constructor" of the parent class must be executed first ")
    • The reflection calls the class. If the class is not initialized, You need to initialize it first.
    • When a VM is started, classes that contain the main () method must be initialized.
  • Note: static {} and static variable initialization may not occur when the server is started (that is, not necessarily when the class is loaded, execute a piece of code xxx. You can implement spring's InitalizingBean class, rewrite the afterPropertiesSet () method under this interface, and write xxx code into this method.

 

Summary:

  • Class loading process
    • "Loading" Stage 1: Get the binary byte stream that defines this class by using the fully qualified class name of a class
    • "Verification" Phase 1: File Format Verification
    • "Loading" Stage 2: Convert the static storage structure represented by this byte stream into the data structure during running in the method Zone
    • "Loading" Stage 3: generate a java. lang. Class Object in the Method Area, which serves as the access entry for various data of the Class in the method area.
    • "Verification" Stage 2: Metadata Verification
    • "Verification" Stage 3: Verify the bytecode instructions of the method body
    • "Preparation" Stage 1: allocate memory for class variables
    • "Preparation" Stage 2: Set the zero value of the class variable
    • "Verification" Stage 4: Symbol reference verification (followed by "resolution", only when "resolution)
    • "Resolution": converting a symbolic reference to a direct reference (not a step that must be performed before "initialization)
    • "Initialization": Not necessarily when it occurs, but after "loading", "Verification", and "Preparation"
  • With regard to the verification part, we may doubt that, since javac has done a lot of verification in the "syntax analysis" and "Semantic Analysis" sections, why should we perform verification when loading classes?
    • Javac does not perform all verification in the class loading part, such as magic number verification.
    • Not all class files are generated by javac, and third-party jar files, or even self-built class files
  • The above steps are carried out in the Method Area from the second stage of "Verification" to before "initialization". This is also the main place for class loading.

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.