Virtual machine class loading mechanism

Source: Internet
Author: User
Tags array definition export class

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.

Class load Time

Life cycle of a class

Load, validate, prepare, initialize, unload the 5-person phase is deterministic, and the class's loading process must begin in this order, and parsing is not necessarily: it can in some cases begin after the initialization of the node, which is a runtime binding that supports the Java language for the class. For the initialization phase, the virtual machine specification strictly specifies that the class has and only 5 of cases must initialize the class immediately.

    • When you encounter the 4 bytecode of new, getstatic, putstatic, or invokestatic, if the class has not been initialized, you need to trigger its initialization first. The most common Java scenario for generating these 4 instructions is when instantiating an object using the New keyword, reading or setting a static field of a class (except for a static field that is final decorated, has placed the result in a constant pool at compile time), and a static method that invokes a class.

    • When you use the Java.lang.reflect package method to make a reflection call to a class, you need to trigger its initialization first if the class has not been initialized.

    • 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.

    • When the virtual machine starts, the user needs to specify a main class to execute, and the virtual opportunity initializes the main class first.

    • When using dynamic language support for JDK1.7, if the final parsing result of a Java.lang.invokeMethodHandle instance is a method handle of ref_getstatic,ref_putstatic,ref_invokestatic, And the class that corresponds to this method handle is not initialized, you need to trigger its initialization first.

The behavior in the above scenario is called an active reference to a class, except that all methods of referencing a class do not trigger initialization, called a passive reference. The passive reference scenario has: 1 referencing a static field of the parent class through a subclass does not cause subclasses to initialize, 2 references the class through an array definition, does not trigger initialization of this class, 3 constants are stored in the constant pool of the calling class in the compilation phase, and there is no direct reference to the class that defines the constant, so initialization of the class that defines

The process of class loadingLoad

During the load phase, the virtual machine needs to complete the following 3 things to see

    • A binary byte stream that defines this class is obtained 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 memory as a access entry for various data of this class in the method area.

The loading phase of a non-array class is the most controllable for the developer, as opposed to the other stages of class loading, because the load phase can be done either by using the system-provided boot class loader or by a user-defined ClassLoader. For an array class, the array class itself is not created by the ClassLoader of the class, it is created directly by the Java Virtual machine. The process of creating an array class requires the following rules:

    • The component type of an array class is a reference type, and the load process defined in this section is used recursively to load the component type, and array C is identified on the class name space of the class loader that loads the component type.

    • If the component's component type is not a reference type, the Java Virtual machine will mark the array C as associated with the bootstrap ClassLoader.

    • The visibility of an array class is consistent with the visibility of its component type, and if the component type is not a reference type, the visibility of the array class will default to public

Verify

The purpose of validation is to ensure that the class file's byte stream contains information that conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself. The verification phase is approximately 4 stages of verification process: file format verification, metadata validation, bytecode verification, reference symbol validation.

    • File format validation: Verifies that the byte stream conforms to the specification of the class file format and can be processed by the current version of the virtual machine.

    • Metadata validation: Semantic analysis of the information described in bytecode to ensure that the information it describes conforms to the requirements of the Java language specification.

    • Bytecode verification: Through data flow and control flow analysis, to determine the program semantics is legitimate, logical.

    • Symbol Reference validation: Occurs when a virtual machine converts a symbolic reference to a direct reference, to ensure that the parsing action is performed properly.


Get ready

The prep phase is a phase that formally allocates memory for class variables and sets initial values, and the memory used by these variables is allocated in the method area. There are two concepts to note:

    • This time the memory allocation includes only class variables (variables that are modified by static), not instance variables, and instance variables are allocated in the Java heap along with the object when the object is instantiated

    • In this case, the initial value is typically 0 values of the data type. such as Int=0,boolean=false and so on.

Analytical

The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference. The Association of symbolic references to direct references is as follows:

    • Symbol reference (Symbolic Reference): a symbol reference is a set of symbols to describe the referenced target, the symbol can be any form of the literal, as long as the use of the unambiguous positioning to the target can be.

    • Direct Reference: A direct reference can be a pointer to a target directly, a relative offset, or a handle that can be indirectly anchored to the target. The target of a direct reference must exist in memory.

Parsing actions are primarily for classes or interfaces, fields, class methods, interface methods, method types, method handles, and call Point qualifier 7 class symbol references.

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 module that implements this action is called the class loader.

Class and Class loader

For any class, it is necessary to establish its uniqueness in the Java Virtual machine, together with the class loader that loads it, and the class itself, each with a separate class namespace. This is more popular: compare two classes is "equal", only if the two classes are loaded by the same class loader, it makes sense, otherwise, even if the two classes are from the same class file, the same virtual machine load, as long as the loading of their class loader is different, then the two classes must be different.

Parental delegation 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), which is part of the virtual machine itself, and the other class loader, which uses C + + implementations. These loaders are implemented in the Java language, independent of the virtual machine, and all inherit from the abstract class Java.lang.ClassLoader. It can also be refined into 3 kinds of loaders.

    • Start the ClassLoader (Bootstrap ClassLoader): This classloader is responsible for storing in the <java_home>\lib directory, or in the path established by the-xbootclasspath parameter, and is recognized by the virtual machine ( The class library is loaded into the virtual machine only if it is recognized by file name, such as Rt.jar, if the class library whose name does not match is not loaded in the Lib directory. The startup ClassLoader cannot be referenced directly by a Java program, and when a user writes a custom class loader, if the load request needs to be delegated to the Boot class loader, the null substitution is used directly.

    • Extension class loader (Extension ClassLoader): This loader is implemented by Sun.misc.launcher$extclassloader, which is responsible for loading the <java_home>\lib\ext directory, or all class libraries in the path specified by the JAVA.EXT.DIRS system variable, developers can use the extension class loader directly.

    • Application class loader (Application ClassLoader): This classloader has a sun.misc.launcher$appclassloader implementation. Because this classloader is the return value of the Getsystemclassloader method in ClassLoader, it is generally referred to as the System class loader. It is responsible for loading the class library specified on the user classpath (Classpath), which the developer can use directly, and if the application does not have a custom loader, this is typically the default loader.

This hierarchical relationship between loaders is called a parental delegation model. The parental delegation model requires that the rest of the loader should have its own parent classloader (a composite relationship) in addition to the top-level startup class loader.

The working process of the parent delegation model is that if a class loader receives a request to load a class class, it first does not attempt to load the class itself, but instead delegates the request to the parent ClassLoader to complete, so that all the load requests should eventually be routed to the top-level startup class loader. The child loader tries to load itself only when the parent loader cannot complete the load request itself (it does not find the required class in its search scope).

Destroying parental delegation models
  • The first break occurred before the parent delegation model (before the JDK1.2 release), in the face of existing user-defined loader implementation code, adding a new protected method to Java.lang.ClassLoader after the class was forward compatible JDK1.2 Findclass ()。

  • The second is caused by the defect of the model itself, the parent delegation model solves the basic class unification problem of each class loader well, but if the basic class is back to the user's code, it is not suitable. Therefore, a thread context class loader was added (thread contextual ClassLoader). This classloader can be set by the Setcontextclassloader method of the Java.lang.Thread class, and if it is not set when the thread is created, it will inherit one from the parent thread, and if it is not set at the global scope of the application, the loader defaults to the loading of the application class. Manager such as JDBC,JNDI,JCE,JAXB and JBI are used in this way.

  • The third is due to the user's pursuit of the dynamic nature of the program (Code hot Swap, Module thermal deployment). The key to implementing the modular thermal deployment of OSGi (the Java modularity Standard) is its custom classloader mechanism implementation. Each program module (called Bundle in OSGi) has its own classloader, and when a bundle needs to be replaced, the bundle is replaced with the same loader to implement the hot substitution of the code. In an OSGi environment, the ClassLoader is no longer a tree structure in the parent delegation model, but is further developed into a more complex mesh structure, and when a class load request is received, OSGi searches in the following order:

      • Delegating classes beginning with java.* to the parent ClassLoader load

      • Otherwise delegate the class in the list of delegates to the parent class loader to load

      • Otherwise, delegating classes in the Import list to classes in export delegate to the class loader of the export class bundle to load

      • Otherwise, find the classpath of the current bundle and load it with your own loader

      • Otherwise, if the lookup class is in its own fragment bundle, the class loader that is delegated to the fangment bundle loads

      • Otherwise, find bundles for the dynamic import list, delegate to the corresponding bundle's class loader to load

      • Otherwise, the class lookup fails.


Virtual machine 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.