In-depth understanding of Java virtual Machines (iv)-Class loading mechanism

Source: Internet
Author: User

I. Overview

The virtual machine loads the data of the description class from the class file into the memory, verifies the data, parses and initializes it, and finally forms the Java type that can be used directly by the virtual machine, which is the class loading mechanism of the virtual machine.

Second, the time of class loading

Class starts from being loaded into the virtual machine's memory, and its entire lifecycle includes: Load (Loading), validate (verification), prepare (preparation), Parse (Resolution), Initialize ( initialization), use (using), and unload (unloading) 7 stages. Where validation, preparation, parsing 3 parts collectively referred to as the connection (linking), the sequence, such as the life cycle of the figure 7-1 class


The order of the 5 phases of loading, validating, preparing, initializing, and unloading is determined, and the class loading process must begin in this order.

The Java Virtual Machine specification does not enforce constraints on loading, and is controlled by the specific implementation of the virtual machine. For the initialization phase, there are strict rules and only v conditions must be initialized immediately:

1. When encountering the 4 bytecode directives of new, getstatic, putstatic, or invokestatic, it is necessary to trigger the initialization of the code if it is not initialized.

2, when using the Java.lang.reflect package method to make reflection calls to the class, if the class has not been initialized, you need to first trigger its initialization.

3. When initializing a class, it is necessary to trigger the initialization of its parent class if it finds that its parent class has not yet been initialized.

4. When the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main method), and the virtual opportunity initializes the main class first.

5, when using JDK1.7 Dynamic language support, if a Java.lang.invoke.MethodHandle instance finally parse the result ref_getstatic, Ref_putstatic, ref_invokestatic method handle , and the class that corresponds to the handle is not initialized, you need to trigger its initialization first.

The behavior in these five scenarios is called an active reference to a class, except that all methods that reference the class do not trigger initialization, which is called a passive reference.

Iii. the process of class loading

1. Loading

Loading is a phase of the class loading process. The following 3 things need to be done during the load phase:

1) The binary byte stream that defines this class is obtained through the fully qualified name of a class.

2), transform the static storage structure represented by this byte stream into the runtime data structure of the method area.

3), generate a Java.lang.Class object representing this class in memory as the access entry for various data of this class in the method area.

2. Verification

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. Verification phase is very important, whether this stage is rigorous, directly determines whether the Java virtual machine can withstand malicious code attacks, from the point of view of performance, the verification phase of the workload in the virtual machine class loading subsystem also accounted for a significant part. Verification will roughly complete the following 4 phases of the Verification action: file format validation, metadata validation, bytecode verification, symbolic application verification.

3. Preparation

The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, which are assigned in the method area. First, the memory allocation at this time includes only class variables, not instance variables, and the instance variables are allocated in the Java heap along with the objects as they are instantiated. Second, what is described here as "typically" is a 0 value of the data type, assuming that a class variable is defined as: public static int value=123; Then the initial value of the variable value after the prep phase is 0 instead of 123. An action that assigns value to 123 will not be executed until the initialization stage.

4. Analysis

The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference.

Symbol reference (Symbolic References): a symbol reference is a set of symbols that describe the target referenced by the reference, and the symbol can be any form of literal, as long as it can be used without ambiguity to locate the target. The symbolic reference is independent of the memory layout implemented by the virtual machine, and the referenced target is not necessarily loaded into memory. The memory layouts implemented by various virtual machines can be different, but the symbolic references they can accept must be consistent, since the literal form of the symbolic reference is clearly defined in the Java Virtual Machine specification's class file format.

Direct reference: (direct References): Directly refers to a pointer directly to the target, a relative offset, or a handle that can be indirectly anchored to the target. The direct reference is related to the memory layout implemented by the virtual machine, and the same symbolic reference is generally not the same as the direct reference translated on different virtual machine instances. If there is a direct reference, the referenced target must exist in memory.

Parsing actions are mainly for classes or interfaces, fields, class methods, interface methods, method types, method handles, and call Point qualifier 7 class symbol references, respectively, corresponding to the constant pool of constant_class_info, Constant_fieldref_info, Constant_methodref_info, Constant_interfacemethodref_info, Constant_methodtype_info, CONSTANT_MethodHandle_ Info and Constant_invokedynamic_info 7 types of constants.

5. Initialization

The class initialization phase is the last step in the class loading process, and this phase really starts executing the Java program code defined in the class.

The initialization phase is the process of executing the class constructor () method.

Four, class loader

The virtual machine design team takes the "fully qualified name of a class to obtain a binary byte stream that describes this class" in the class-loading phase, which is implemented outside the Java virtual machine, so that the application can decide for itself how to get the required class. The code module that implements this action is called the class loader.

1. Parental assignment model

From the point of view of a Java virtual machine, there are only two different classloader: one is to start the ClassLoader (Bootstrap ClassLoader), a part of the virtual machine, and all other ClassLoader, independent of the virtual machine, And all inherit from the abstract class Java.lang.ClassLoader.

Most Java programs use the Boot class loader (Bootstrap ClassLoader), the extension ClassLoader (Extension ClassLoader), the application ClassLoader (application ClassLoader) These three system-supplied class loaders.

The parental delegation model requires that the rest of the ClassLoader should have its own parent classloader, in addition to the top-level startup class loader. The parent-child relationship between class loading is generally not implemented as an inheritance (inheritance) relationship, but is the code that combines (composition) relationships with the parent loader. Figure 7-2 Class loader parental delegation model


The working process of the parent delegation model is that if a classloader receives a request for a class load, it first does not attempt to load the class itself, but instead delegates the request to the parent class loader, which is the case for each level of the ClassLoader, so all load requests should eventually be routed to the top-level startup ClassLoader. The child loader tries to load itself only when the parent loader has feedback that it cannot complete the load request.

2. Destroy the parental assignment model

This article comes from the-JVM advanced features and best practices for deep Java virtual machines---zhou Zhihua. If infringing, please contact the author to delete.

In-depth understanding of Java virtual Machines (iv)-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.