Java Virtual machine--Virtual machine class loading mechanism

Source: Internet
Author: User
Tags array definition constant definition visibility

Virtual machine class loading mechanism

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.

The life cycle of a class is as follows:

--> 验证 --> 准备 --> 解析 --> 初始化 --> 使用 --> 卸载

The three phases of validation, preparation, and parsing belong to the connection process. Parsing can occur after initialization, because Java supports dynamic binding , or runtime binding.

In the following 5 cases, the class must be initialized immediately:

    • Encounters new, Getstatic, putstatic, or invokestatic these bytecode directives. Specifically, you use the New keyword to instantiate an object, read or set a static field for a class (except for static fields that are final decorated, that have been put into a constant pool for the duration of the compilation public final static String HELLO = "Hello"; ).
    • Java.lang.reflect the method of the package is called when the class is reflected, it needs to be initialized first if it is not initialized.
    • When initializing a class, if the class has a parent class, the parent class must first be initialized
    • For a virtual machine to start, the user needs to specify a main class to execute (the class with the Main method), and the virtual opportunity initializes the main class, which is the entry for the program.
    • A java.lang.invoke.MethodHandle instance finally resolves the result is a method handle of Ref_getstatic, Ref_putstatic, ref_invokestatic, and the corresponding class of this method handle has not been initialized, You need to trigger its initialization first.

The above 5 cases are called active references to a class. The rest of the situation is called a passive reference. Take a look at the case of passive references;

    • The subclass inherits a static field from the parent class, and when it accesses the static field inherited from the parent class through the subclass, it only triggers the initialization of the parent class without triggering the initialization of the subclass, only the class that directly defines the field is initialized.
    • Referencing a class through an array definition does not trigger initialization of this class, such asMyObject[] objs = new MyObject[10]
    • Constants are stored directly in the constant pool of the calling class at compile-time, not directly referencing a class that defines a constant, and does not trigger initialization of the class. If there is a static field in the MyObject class public final static String HELLO = "Hello" , the initialization is not triggered when Hello is called.

Interfaces also have initialization, the difference between the initialization of a class: When an interface is initialized, it does not require that the parent interface be initialized, but the parent interface is initialized when the parent interface is used.

Load

The following three things are done during the load phase:

    • Gets the binary byte stream that defines the class through the fully qualified name of the class.
    • Convert the static storage structure represented by the above byte stream into the runtime data structure of the method area.
    • Generate a Java.lang.Class object representing the class in memory as the access entry for the various data structures of this class in the method area

Loading of non-array classes can be done using the system-provided boot class loader or by using a custom class loader.

The array class itself is not created by the ClassLoader, but is created directly by the Java Virtual machine, but the element type of the array class (such as Object in Object[] object Object[][] ) is ultimately created by the class loader.

There are two types of elements, reference types and basic types.

    • If the component type of the array (the type of the array minus one dimension) is a reference type, the component type is recursively loaded, and the array class is identified on the class name space of the class loader that loads the component type.
    • If the array's component type is not a reference type, such as the Int[],java virtual machine will mark the array class as associated with the boot class loader.
    • The visibility of an array class is consistent with the visibility of its component types, and if the component type is not a reference type, the visibility of the array is public by default.
Verify

The verification phase consists of the following 4 tests:

    • file format Validation . The main checks whether the byte stream conforms to the class file specification, such as whether to start with 0xCAFEBABE, whether the main, minor version number is within the current virtual machine processing range, etc...
    • meta-data validation . This is primarily a semantic analysis of the information described in bytecode, such as checking if the class has a parent class, whether the parent of the class inherits from a class that is not allowed to inherit. The fields in the class, whether the method conflicts with the parent class, etc...
    • byte code verification . Through the analysis of data flow and control flow, it is determined that program semantics is legal and logical. In this stage, the method body of the class is verified and analyzed to ensure the security of the Java Virtual machine. such as guaranteed jump instruction does not jump to the method body outside the byte code instruction, guarantees the method body type conversion valid and so on ...
    • symbol Reference Validation . Can be thought of as matching checks on information other than the class itself (the various symbol references in a constant pool). If the fully qualified name described by the string in the symbol reference can find the corresponding class, whether the class, field, method's accessibility (public, private, and so on) in the symbol reference can be accessed by the current class.
Get ready

Formally allocates memory for class variables and sets the initial values of class variables (static adornments), which are typically "0 values", such as 0 for int, and False for Boolean. The following example:

publicstaticint9;

After the prep phase , the initial value is 0 instead of 9,val is assigned a value of 9 in the initialization phase .

But if it is

publicfinalstaticint9;

Because there is a final modification, Val is assigned a value of 9 in the prep phase.

Analytical

A virtual machine replaces a symbolic reference within a constant pool with a direct reference procedure.

    • symbol Reference . A set of symbols to describe the target of the lock reference, the symbol can be any form of the literal, as long as the use can be used without ambiguity to locate the target.
    • Direct Reference . Can be a pointer to a target directly, a relative offset, or a handle that can be indirectly anchored to the target.

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.

Parsing of classes or interfaces

If the current class is D, to parse a never-parsed symbol reference n into a direct reference to a class or interface, the following three steps are required:

    • C is not an array type. The virtual opportunity passes the fully qualified name of N to the class loader of D to load C. If C has a parent class or an implemented interface, additional loading is also triggered.
    • C is an array type, and the element type is an object, if Integer[10] . The array element type is loaded according to the above rules (in this case, an integer), and then the virtual machine generates an array object representing this array dimension and the object (here, 10 and integer, respectively).
    • If there is no exception to the above procedure, C has become a valid class or interface in the virtual machine. But before parsing is complete, you also check if D has access to C, otherwise it throws an exception.
Field resolution

The symbolic reference of the class or interface to which the field belongs is resolved first. If the resolution succeeds, the class or interface to which the field belongs is represented by C. Search for subsequent fields of C after

    • c If a field that contains a simple name and a field that describes the match of the Betta target, returns a direct reference to the field, and the lookup returns.
    • Otherwise, if the interface is implemented in C, each interface and its parent interface will be searched recursively, and if the interface contains a simple name and a field where the field description matches the target, the direct reference to the field is returned, and the lookup is completed;
    • Otherwise, if C is not java.lang.Object, the parent class will be searched recursively from top to bottom, if the parent class contains a simple name and the field description matches the Target field, then return the direct reference to the field, the end of the lookup;
    • Otherwise, the lookup fails, throwing an exception.

When a reference is successfully returned during a lookup, the field will be authenticated and an exception will be thrown if no access to the field is found.

class method parsing

The symbolic reference of the class or interface to which the method belongs is parsed first. If the parsing succeeds, the class to which the field belongs is represented in C. After the C

    • A constant definition of a symbolic reference to a class method and an interface method is separate, and an exception is thrown if the C in the Class_index is found to be an interface in the class method table.
    • If through the above steps, and the same as field resolution, first found in Class C, if there is a simple name and description of the Fu Du fish target matching method, then return the direct reference to the method, find the end;
    • Otherwise, a recursive lookup in the parent class of Class C;
    • Otherwise, the list of interfaces implemented in Class C and the total recursive lookup of their parent interface, if there is a matching method, indicates that C is an abstract class, throws an exception, and finds the end.
    • Otherwise, the lookup fails.

If the lookup succeeds and the direct reference is returned successfully, the method is granted permission validation and throws an exception if it finds no access to this method.

Interface Method Parsing

The symbolic reference of the class or interface to which the method belongs is parsed first. If the resolution succeeds, the interface to which the field belongs is represented by C. After the C

    • Throws an exception if the C in the Class_index index in the interface method table is found to be a class.
    • Otherwise, look in interface C;
    • Otherwise, recursively finds in the parent interface of interface C until java.lang.Object (including object)
    • Otherwise, the lookup fails.

Because the methods in the interface are public, there are no access rights issues like the one above.

Initialization

The initialization phase does not really start executing the Java program code defined in the class. The initialization phase is the process of executing the class constructor ( <clinit>() not the instance constructor <init>() ).

publicstaticint9;

In the Prep phase Val is 0, and at the initialization stage Val is assigned a value of 9.

    • <clinit>()Generation: The assignment of all class variables in the compile-time auto-collection class and the statement merge of the static statement block, the static{} block. The order of automatic collection and the order in which the statements appear in the file are consistent.
    • The class constructor <clinit>() is different from <init>() the need to explicitly call the parent class constructor, and the virtual machine guarantees that the child class is executed before the execution of the <clinit>() parent class <clinit>() ;
    • <clinit>()It is not necessary for a class or interface to generate a method for this class if there is no static statement block in a class, and no assignment is done to the class variable <clinit>() .
    • The parent class <clinit>() executes first, so the static static statement block of the parent class is preceded by the execution of the subclass;
    • A static statement block cannot be used in an interface, and a method is generated <clinit>() , but unlike a class, a parent class interface is not triggered by executing an interface, and the <clinit>() <clinit>() parent class is initialized only if a variable defined in the parent class is used;
    • In multi-threading, if there are multiple threads initializing a class at the same time, only one county can execute the method of the class, and the <clinit>() other threads will block until the thread <clinit>() finishes executing.
Class Loader

Class loader: Gets a binary byte stream that describes this class by using the fully qualified name of a class.

Any class needs to determine the uniqueness of the Java Virtual machine together with the class loader loading it and the class itself, each of which has a separate class namespace, in layman's terms: Compare whether two classes are "equal" and only make sense if the two classes are the same class loader. Even if two classes are from the same class file and are loaded by the same Java virtual machine, the two classes are not equal as long as they are not loaded by the same classloader.

Parental delegation Model

For the JVM, there are only two different classloader:

    • Start the ClassLoader, which is part of the virtual machine;
    • Other ClassLoader, independent of the virtual machine, inherit from Java.lang.ClassLoader

Then subdivide the words

    • Starts the class loader,
    • Extension class loader, responsible for loading
    • The application loader, which is responsible for loader user class path Classpath on the specified class library, is usually the default class loader in the program.

Applications are loaded with each other by these three kinds of loaders, whose relationships are typically presented in the parent delegation model. Parental delegation Model: In addition to the top-level startup ClassLoader, the other class loaders should have their own parent ClassLoader. The parent-child relationship here is typically a combination rather than an inheritance.

Parent delegation Model work process: A class loader receives a request for a class load, which first does not load the class itself, but instead delegates it to the parent class, so the final request is routed to the top-level startup class loader, and the subclass tries to load itself only when the parent class is unable to complete the load request.

Advantages of the Parental delegation model: TheJava class has a hierarchical relationship with precedence as its ClassLoader . For example, the Java.lang.Object class, stored in the Rt.jar, no matter which class loader to load this class, and finally delegated to the top of the startup class loader to load, so the object class in the program's various loader environment species are the same class .

Parental delegation Model implementation: first check whether it has been loaded, if there is no way to call the parent loader, if the loadClass() parent loader is empty, use the startup ClassLoader as the parent loader, if the parent loader fails to load, throws an exception after calling its own findClass() to load.

by @sunhaiyu

2018.6.11

Java Virtual machine--Virtual machine class loading mechanism

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.