Analysis of class loading process

1. Load
    Load (loading) stage is the "class loader" stage (Class Loading) process, in loading stage, the virtual machine needs to do three things:

    1) to obtain the fully qualified name is defined by such a class of binary byte stream.

    2) the byte stream that represents the static storage structure into a run-time data structure area method

    3) generates a representative of the Java heap java.lang.Class object of this class, as a method of access to the entrance area of such data.

   Virtual machine specification these three points are not specific, virtual machine implementation and application-specific flexibility considerably. Many loading:

    reading from the zip package, the future development of JAR, EAR, WAR format
    acquired from the network, which is the most typical scene Applet
    calculates and generates runtime, this scene is the most used dynamic agent technology in java. in lang.reflect.Proxy, is used to generate a specific ProxyGenerator.generateProxyClass * proxy class interfaces the proxy $ binary byte stream.
    Generated from other files, a typical scenario: JSP application
    read from the database
    . . . .
    After loading, the external virtual machine according to a binary stream of bytes stored in the format required by virtual machines in the process area, the process area data storage format defined implemented by the virtual machine itself, specifically the virtual machine specification data in this area is not predetermined structure. Then Java heap java.lang.Class instantiate an object class, the object as an external interface access method program area these types of data. Part of the load phase and the connection phase (e.g., a portion of the file format byte code verification operation) is carried out crossing, loading stage has not been completed, the connection phase may have started, but they caught in the loading stage of the operation, is still a connection content phase, the two phases starting time remained fixed sequence.

2. Verify
    to verify the connection phase is the first step of this phase is designed to ensure that the information byte stream Class file contains meet the requirements of the current virtual machine and the virtual machine will not jeopardize their own safety.

    Virtual Machine specification of restrictions and guidelines at this stage is very general and just said something to verify if the byte stream input file storage format does not meet the Class, you throw a java.lang.VerifyError anomaly or a subclass exception. What specific aspects should check, how to check, when checked, they are not mandatory or explicitly stated, so different virtual machines to verify the implementation may vary, but generally a four-stage inspection process will be completed the following fields: verification file format, metadata validation, verification and symbolic references bytecode verification.

    1. Verify file format
    of the first stage to verify whether the byte stream file format specifications Class NO, and can be the current version of virtual machine processing. The main purpose is to ensure the verification phase of the input byte stream can be correctly interpreted and stored in the method area, a Java fit the description of the type of information format requirements. This verification is based on the phase of the byte stream, after the hungry validation segment, the byte stream will enter the region of memory storing method, so the back three phases are all verification method based on the storage area of the configuration performed .

    2. metadata validation
    The second stage is the byte code description information semantic analysis to ensure that the information which describes the Java language meet regulatory requirements, this phase may include verification points as follows:

    if the class has a parent class (except java.lang.Object outside, all classes should have a parent)
    parent class if the class is not allowed to inherit the inherited class (the final modified)
    If the class is not an abstract class, whether realized their parent class or interface implementation requirements all methods.
    Class field, whether the method had a conflict with a parent class
    . . . . .
   Bytecode verification 3.
    The third stage is the most complex verification process a, whose main job is data flow and control flow analysis. After the second stage of the metadata information in the data type checking done, this stage of the process will check body class analysis. This phase of the mission is to ensure the method validation class at runtime virtual machine security will not make harm behavior, such as:

    to ensure that data type and sequence of instruction codes at any time operand stack can work together, for example, does not appear this situation is similar to: int placed a stack operation in the type of data, a long press Shique type loaded in the local variable table.
    Ensure not jump to the jump instruction bytecode instructions other than the method body.
    Assurance method body type conversion is effective, for example, can be assigned to the object is a subclass of the parent class data type, which is safe, the converse is not legitimate.
    . . . . . .
    If the bytecode body of a class method did not pass the bytecode verification, it is certainly a problem; if a method body by the byte code verifier can not explain it necessarily safe. Even bytecode verification being carried out a number of checks, it can not be guaranteed. This involves discrete mathematics in a very well-known problems "Halting Problem": that popular argument is that, through the program to check program logic can not be absolutely accurate - the program can not accurately check whether the program can be limited within the end of the run time.

    To avoid excessive consumption of time in the bytecode verification stage, then 1.6 Code attribute table attribute added to the method body in an attribute called "StackMapTable", and the attribute describes a method of substantially all the weight of the block start local variable table and the proper operation of the stack state, which can be verified byte code into a type inference save some time type checking. Use -XX: -UseSplitVerifier option to close off this optimization, or use the parameters -XX: + FailOverToOldVerifier requirements when validation fails types of Swiss back to the old way of type inference check (not allowed after 1.7).

    4. Verify reference symbols
    final stage parity generating symbolic references in the virtual machine into direct reference time, the conversion operation would be the third phase of the connection - Analytical phase occurs. Verification of symbolic references can be seen as information other than the type itself of the matching check, usually need to verify the following:

    whether the correspondence can be found by the fully qualified class name string symbolic references described.
    Whether there is a coincidence method descriptor word and the name of the described method is simple and fields in the specified class.
    Access class, field and method references a symbol in (private, protected, public, default ) whether the current class can be accessed.
    . . . . . .
    The purpose is to ensure the verification of symbolic references analysis operation can be performed properly. If not verified by reference symbol, an exception will be thrown a java.lang.IncompatibleClassChangeError subclasses, such as java.lang.IllegalAccessError, java.lang.NoSuchFieldError, java. lang.NoSuchMethodError and so on.

    The validation phase for class loading mechanism of the virtual machine, it is a very important, but not necessarily essential stage. If all the code running and have been repeatedly proven in the implementation phase could consider using -Xverify: none parameter to shut down most of the class verification measures to lock a single virtual machine class load time.

3. Prepare the
    preparation phase is formally allocate memory for class variables and class variables set worth the initial stage, this memory will be allocated in the method area. When this stage there are two concepts prone to confuse the need to emphasize that this is the first time for memory allocation includes only class variables (static variables modified), and does not include the instance variables, instance variables will be instantiated in the object sleeping together heap allocated objects in Java. Followed by the initial value here "Often" is the data type of zero value.

    public static int value = 123;

    this time value is initialized to 0 instead of 123. If the present field attribute table ConstantValue class attribute field, and that in the preparation stage variable value is initialized to the value specified by the property ConstantValue, such as:

    public static int Final value = 123;

    the Javac property value to be generated at compile time ConstantValue in the preparatory phase of the virtual machine will be based ConstantValue setting value assigned to 123.

4. resolve
    Parsing stage is a constant pool of virtual machine symbols replace references made direct reference to the process.

    Reference symbol (Symbolic References): Symbol reference to a certain set of symbols to describe the referenced symbol can literal in any form, can be positioned unambiguously as long as the goal to use. Irrespective of symbolic references to memory layout of the virtual machine implementation, the goal is not necessarily a reference has been loaded into memory.

    A direct reference (Direct References): direct reference may be direct pointer to the object, or a relative offset can be targeted to the target profile handle, associated with direct reference to the memory layout of the virtual machine implementation, unified at different reference symbols translated from the virtual machine instance is generally not a direct reference to the same, if you have a direct reference to that target reference must already exist in memory.

     Among the virtual machine specification does not provide a specific time resolution phase occurs only required in the implementation of anewarray, checkcast, getfield, getstatic, instanceof, invokeinterface, invokespecial, invokestatic, invokevirtual, multianewarray, new, putfield and 13 for operating this putstatic before bytecode instructions character references, they use the first reference symbol parsing.

    The main analysis operation for the class or interface, fields, methods class, interface method references in four symbols, each corresponding to the constant pool CONSTANT_Class_info, CONSTANT_Fieldref_info, CONSTANT_Methodref_info CONSTANT_InterfaceMethodref_info and four kinds of constant type. Here to explain the process to resolve these four references.

1. Analytical class or interface
    is assumed in which the current code class is D, if we want a parsed never resolve symbolic references to N directly reference a class or interface C, then the virtual machine needs to parse through the process comprising the following three steps:
    1) If the type is not an array C, and that the virtual machine is transmitted N represents the fully qualified name of a class loader to load the class D C. In the loading process, since no data validation, bytecode verification need be loaded in turn may trigger other actions related classes, such as loading the parent of this class or interface implemented. Once the loading process there are any abnormalities, the resolution process will be failed.

    2) If C is a type of an array, and the array element type is the object descriptor is N will be similar "Ljava.lang.Integer" forms, which will load the array element type according to the rules of the first point. If N descriptor assumed as comprehensive form, the type of the element is to be loaded "java.lang.Integer", then generates an array of objects by the virtual machine and the number of elements of the representative set of dimensions.

2. Analytical fields
    to be parsed through a unresolved symbol references in the field, the index of the first entry in the stack class_index CONSTANT_Class_info symbol field table references are resolved, i.e. symbol class or interface reference field belongs. If there are any anomalies in the process of parsing the class or interface symbols cited, the field will result in failure to resolve the symbolic references. If the resolution is completed successfully, it will belong to the class or interface of this field is represented by C, C Virtual Machine Specification requirements for subsequent search field according to the following steps:

    1) if C itself contains a simple name and the target segment descriptor word field match, it returns a direct reference to this field, to find the end.

    2) Otherwise, if you implement the interface in C, it will be in accordance with the inheritance from the recursive searching down each interface and its parent interface. If the interface contains a simple field names and field descriptors are matched with the target, this field is returned direct reference to find the end.

    3) Otherwise, if C is not java.lang.Object, it will follow the inheritance from the parent class recursive searching down, if the interface contains the field names and field descriptors are simple and objective matches Returns direct reference to this field, to find the end.

    3) Otherwise, the lookup fails, an exception is thrown java.lang.NoSuchFieldError.

   If the search returns a reference to the process is successful, it will be on the field to verify permissions, if found not to have access to the field, java.lang.IllegalAccessError will throw an exception.

3. Analytical Method class
    class method resolution as a first step and the analytical fields, parsing the line interface class or method class_index symbol index item belongs references, if successfully resolved, this class represents written in C, virtual machine in accordance with the steps of point method subsequent search categories:

    constant type definition 1) class methods and interface method reference symbols are separated, if it is found in the class method table index C is class_index interfaces, it is thrown directly java.lang.IncompatibleClassChangeError exception.

    2) When the first step (1), to find whether there is in category C simple name and descriptor of the target match, if there is a direct reference to returns to this method, search ends.

    3) Otherwise, the parent class of class C recursively find whether there is this method, this method is returned if there is a direct quote, find an end.

    4) otherwise, in the list of interfaces implemented in C class and their parent interface recursive method to find out whether there is this, if there is a match, indicating that the class C is an abstract class, find the end of this time, an exception is thrown java.lang.AbstractMethodError .

    5) Otherwise, declaring method lookup fails, throw java.lang.NoSuchMethodError.

    Finally, if the process is successfully returned to find a direct reference, this method will verify permissions; if it is found not to have access to this method, an exception will be thrown java.lang.IllegalAccessError.

4. Analytical Method Interface
    Interface methods also need to parse out the method of the class or interface class_index symbol entry interface method table index references belongs, if successfully resolved, this interface represents still written in C, for the next virtual machine will follow the following procedure interface Search method:
    1) and class methods to resolve the contrary, if it is found at the interface method table class_index index C is a class rather than an interface, it is a direct throw java.lang.IncompatibleClassChangeError exception.

    2) Otherwise, if there is to find in the interface this method, if the method returns a direct reference to find the end.

    3) Otherwise, the parent Interface Interface C in a recursive lookup until java.lang.Object class, to see if there is this method, this method is returned if there is a direct reference to find the end.

    4) No person, declaring method lookup fails, an exception is thrown java.lang.NoSuchMethodError.

    Because the interface methods are public so there is no IllegalAccessError exception.

5. Initialize the
   Java program really started until initialization class defined in the code. During the initialization phase is performed class constructor <clinit> () method.

<clinit> () method is an assignment statement blocks and static action statement automatically by the compiler to collect all of the class class variables merger collected sequentially in the source file depends occur. Static statement block only access to the static variables defined in a block of statements before, the definition of variables after it, you can copy the statement in front of a static block, but can not be accessed.
<clinit> () constructor method with a different class, it does not need to call the parent class constructor display, before the virtual machine to ensure that the subclass <clinit> () method performs, parent class <clinit> () method has been performed completed. Thus Class <clinit> () method of the first virtual machine to be executed certainly java.lang.
As the parent of <clinit> () method performs first, which means a static block of statements as defined in the parent class takes precedence over variable subclass assignment.
If a class is not a static variable or a static block of statements, the compiler may not be generated for the class <clinit> () method.
The interface can not use the static code block, but may use a static variable. Unlike classes that implements the interface <clinit> () method does not need to run a parent interface <clinit> () method. Only the parent variable defined in the interface is the interface will be initialized using the parent addition, as in the class that implements the interface does not perform initialization page <clinit> () interface method.
Virtual opportunity to ensure that a class <clinit> () method is properly locked and synchronized in a multithreaded environment. Multi-threaded access, a visit the other are blocked.
                                                                                                                                                          ---- This switched blog Park

Guess you like

Origin www.cnblogs.com/zhuxiaopijingjing/p/12306279.html